gpt4 book ai didi

c - 读取C txt文件的问题

转载 作者:太空宇宙 更新时间:2023-11-04 08:32:35 24 4
gpt4 key购买 nike

我正在制作一个 C 程序,我需要它在用户关闭程序时保存一些整数和字符串。我成功地做到了。 txt 文件已创建并且所有内容均已正确编写,问题是,当我尝试在编译器上读取它时,它无法正常工作。我的代码是:写:

saveFile = fopen("saveFileP.txt", "w");
for (int i=0; i<numberofPeople; i++) {
fputs(people[i].firstName, saveFile);
fputs(" ", saveFile);
fputs(people[i].lastName, saveFile);
fputs(" ", saveFile);
fprintf(saveFile, "%d ", people[i].cash);
fprintf(saveFile, "%d ", people[i].position);
fprintf(saveFile, "%d ", people[i].inGame);
}

阅读:

saveFile = fopen("saveGameP.txt", "r");
for (int i=0; i<numberOfPeople; i++) {
fgets(people[i].firstName, 20, saveFile);
fgets(people[i].lastName, 20, saveFile);
fscanf(saveFile, "%d", &people[i].cash);
fscanf(saveFile, "%d", &people[i].position);
fscanf(saveFile, "%d", &people[i].inGame);
}

然后我要求它将值打印到屏幕上,它写入了错误的值,但在 txt 文件中值是正确的。我究竟做错了什么?谢谢。

PS:我使用的是 Xcode。

最佳答案

尝试

for (int i=0; i<numberOfPeople; i++) {
fscanf(saveFile,"%s %s",people[i].firstName,people[i].lastName);

fscanf(saveFile, "%d", &people[i].cash);
fscanf(saveFile, "%d", &people[i].position);
fscanf(saveFile, "%d", &people[i].inGame);
}

我使用了 fscanf() 因为 fgets() 读取整行直到遇到 \n 字符(或直到遇到最多读取 20 个字符),直到找到空格。由于 firstNamelastName 都由空格分隔,您可以使用 fscanf()

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

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