我尝试用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个以are n't逗号(将是名称)组成的字符序列,然后继续进行操作其他数字以逗号分隔。
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