![](/img/trans.png)
[英]Why my fscanf does not read the first string but reads the last line into the first string instead?
[英]Why does fscanf only read the first word of one string from file
当我尝试使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.