gpt4 book ai didi

c - 为什么 fscanf 只从文件中读取一个字符串的第一个单词

转载 作者:行者123 更新时间:2023-11-30 20:29:01 25 4
gpt4 key购买 nike

当我尝试使用 fscanf() 读取结构的文件信息时遇到问题。它只读取字符串的第一行,循环永远不会结束。我该如何解决这个问题?

结构体

typedef struct {
int id;
char name[80];
char nameStadium[80];
int numberPlacesStadium;
float funds;
float monthlyExpenses;
int active;
} Team;

我用这个代码来阅读

void showAll(void)
{
FILE* file;
Team team;

file = fopen("file.txt", "rt");

if (file == NULL)
{
printf("!!!Cant open file!!!\n");
return;
}

rewind(file);

printf("\n\n=== TEAMS ======\n");
printf("%s\t%s\n", "ID", "NAME");

while (fscanf(file, "%6d %s %s %6d %f %f %03d\n", &team.id, team.name, team.nameStadium, &team.numberPlacesStadium, &team.funds, &team.monthlyExpenses, &team.active) != EOF)
{
if (team.active != 0)
{
printf("%d\t%s\n", team.id, team.name);
}
}

fclose(file);

}

我不明白为什么fscanf()只获取第一个单词而不是完整的字符串

有人知道如何解决这个问题吗?

最佳答案

我刚刚使用我按照您发布的格式制作的示例文本文件测试了您的代码。一切都已读入,除了您没有正确关闭文件之外,一切似乎都很好。它应该看起来像这样。

fclose(file);

如果您希望代码能够读取带有空格的字符串,最好的选择是使用分隔符系统。下面的代码读取它们的类型(假设整数之间没有空格),读取 80 个不是逗号的字符序列(这将是名称),以及然后继续处理以逗号分隔的其他数字。

  while (fscanf(file, "%d, %80[^,], %80[^,], %d, %f, %f, %d\n", &team.id, 
team.name, team.nameStadium, &team.numberPlacesStadium, &team.funds,
&team.monthlyExpenses, &team.active) != EOF)
{
if (team.active != 0)
{
printf("%d\t%s %s\n", team.id, team.name, team.nameStadium);
}
}

我已经测试过它的工作原理,它确实有效,但请记住,这也不是最优雅的解决方案。

这些是我的文本文件中的行的样子:

 133222, Bears, Bears Stadium, 444333, 23, 35.3, 52
666222, Eagles, Eagles Stadium, 322222, 13, 56.3, 54

关于c - 为什么 fscanf 只从文件中读取一个字符串的第一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59441696/

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