我在使用fscanf()
传递结构指针到函数时遇到问题。
这是我的结构:
typedef struct {
int health;
int y;
int z;
} save;
在main
中,我有:
save save = { 0 }; //init with zeros
loadgame(&save);
health = save.health;
和我的函数loadgame()
看起来像这样:
bool loadgame(save* save) {
FILE* fptr;
fptr = fopen("savegame.txt", "r");
if (fptr == NULL)
return 0;
fscanf(fptr, "health= %d", save->health);
return 1;
};
我的savegame.txt
文件有一行:
health= 5
并且我的函数没有更改save->health
,完成此函数后,我的健康状况为零。
我试图那样做我的功能,并且它在我更改的功能loadgame()
中也具有相同的解决方案
fscanf(fptr, "health= %d", save-health);
to
fscanf(fptr, "health= %d", &(save-health));
fscanf(fptr, "health= %d", save->health);
-> fscanf(fptr, "health= %d", &save->health);
您在这里有可以和https://godbolt.org/z/5CuZwR一起玩的地方
例如,在我的示例中,[[总是检查scanf
的结果
您需要做
fscanf(fptr, "health= %d", &save->health);
因为->优先于&,这将为您提供健康成员的地址。
fscanf
需要一个指针,因此它知道将值保存在何处。除此之外,您的代码还有很多其他小问题。我已经在下面的评论中解决了这些问题:#include <stdio.h>
#include <stdbool.h>
typedef struct {
int health;
int y;
int z;
}save_tp;
//using the same name for a typedef and a variable is a bad idea;
//typedef struct{...} foo; foo foo; prevents you from declaring other varibles of type foo
//as the foo variable overshadows the foo typedef name;
//better give types a distinct name
bool loadgame(save_tp* save){
FILE* fptr;
fptr = fopen("savegame.txt", "r");
if (fptr == NULL)
return false;
bool r = (1==fscanf(fptr, "health= %d", &save->health)); //needs an address + may fail
fclose(fptr); //need to close the file or you'd be leaking a file handle
return r;
} //shouldn't have a semicolon here
int main(void)
{
save_tp save={0};
if (!loadgame(&save)) perror("nok");
else printf("ok, health=%d\n", save.health);
}