gpt4 book ai didi

c - 文件读取错误值

转载 作者:太空宇宙 更新时间:2023-11-04 00:23:49 25 4
gpt4 key购买 nike

我不知道为什么会这样。我有一个结构可以完美地打印到一个文件中,但是当我尝试读出该文件时,我得到的东西甚至与实际存在的东西相去甚远。写/读部分:

int save_data(){
char enter = 0;
int response;
while(true){
printf("1. Add new player\n2. View player data\n3. Return to main");
printf("\nSelection: ");
scanf("%d", &response);
if (response == 1){
FILE* PlayerFile = fopen("players.txt","w");
int i = 0;

for (i = 0; i < 1; i++){
struct player_info aPlayer = create_player();
fprintf(PlayerFile, "Name: %s\nLevel: %d\nStrength Mod: %d\nDexterity Mod: %d\nConstitution Mod: %d\nIntelligence Mod: %d\nWisdom Mod: %d\nCharisma Mod: %d\n", aPlayer.name, aPlayer.Level, aPlayer.Str, aPlayer.Dex, aPlayer.Con, aPlayer.Int, aPlayer.Wis, aPlayer.Cha);
}
fclose(PlayerFile);
return 0;
}

else if (response == 2){
struct player_info aPlayer;{
char name[30];
int Level, Str, Dex, Con, Int, Wis, Cha;
};
FILE* PlayerFile = fopen("players.txt","r");
for (int i = 0; i < 1; i++){
struct player_info create_player;
fscanf(PlayerFile, "Name: %s\nLevel: %d\nStrength Mod: %d\nDexterity Mod: %d\nConstitution Mod: %d\nIntelligence Mod: %d\nWisdom Mod: %d\nCharisma Mod: %d\n", aPlayer.name, &aPlayer.Level, &aPlayer.Str, &aPlayer.Dex, &aPlayer.Con, &aPlayer.Int, &aPlayer.Wis, &aPlayer.Cha);
printf("\nName: %s\nLevel: %d\nStr mod: %d\nDex mod: %d\nCon mod: %d\nInt mod: %d\nWis mod: %d\nCha mod: %d\n\n", aPlayer.name, &aPlayer.Level, &aPlayer.Str, &aPlayer.Dex, &aPlayer.Con, &aPlayer.Int, &aPlayer.Wis, &aPlayer.Cha);
}

fclose(PlayerFile);
}
else if (response == 3){
false;
break;}
}
}

实际在文件中的输入:

Name: Hamfast Drummond
Level: 9
Strength Mod: 8
Dexterity Mod: 7
Constitution Mod: 6
Intelligence Mod: 5
Wisdom Mod: 4
Charisma Mod: 3

打印上面的结果:

Name: Hamfast
Level: 6422172
Str mod: 6422176
Dex mod: 6422180
Con mod: 6422184
Int mod: 6422188
Wis mod: 6422192
Cha mod: 6422196

现在,我意识到这一行在所有变量之前都缺少 &,但是当我添加它时,它打印到文件的内容是相同的错误数字,并且读出是正确的那种情况,但它没有将我输入的内容打印到文件中。

作为附带问题,如果允许二合一,我也希望它打印全名而不仅仅是第一个,但我不确定该怎么做。

最佳答案

printf需要带有 %d 格式说明符的值,而 scanf 需要引用

这个:

printf("\nName: %s\nLevel: %d\nStr mod: %d\nDex mod: %d\nCon mod: %d\nInt mod: %d\nWis mod: %d\nCha mod: %d\n\n", aPlayer.name, &aPlayer.Level, &aPlayer.Str, &aPlayer.Dex, &aPlayer.Con, &aPlayer.Int, &aPlayer.Wis, &aPlayer.Cha);

必须是

printf("\nName: %s\nLevel: %d\nStr mod: %d\nDex mod: %d\nCon mod: %d\nInt mod: %d\nWis mod: %d\nCha mod: %d\n\n", aPlayer.name, aPlayer.Level, aPlayer.Str, aPlayer.Dex, aPlayer.Con, aPlayer.Int, aPlayer.Wis, aPlayer.Cha);

换句话说,您(错误地)打印了这些变量的地址,而不是它们的值。

关于c - 文件读取错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42338513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com