当我尝试使用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()
只得到第一个单词而不是完整字符串
有人知道如何解决吗?
答案 0 :(得分:0)
我刚刚按照您发布的格式使用示例文本文件测试了您的代码。一切都已读入,但似乎没有问题,只是没有正确关闭文件。看起来应该像这样。
_handleChange = (name, value) => {
value = value.replace(/[^A-Za-z]/ig, '');
const { data } = this.state;
data[name] = value;
this.setState(
{
data: JSON.parse(JSON.stringify(data))
},
() => {
this._isValid(name)
}
);
};
如果您希望代码能够带空格的字符串读取,那么最好的选择是使用定界符系统。下面的代码读取其类型(假设整数之间没有空格),读取80个不逗号(将是名称)的字符,并且然后以逗号分隔其他数字。
fclose(file);
我已经对其进行了测试,但确实如此,但是请记住,这也不是最优雅的解决方案。
这些是我的文本文件中的行的样子:
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);
}
}