我有一个这样的文件:
name1 nickname1
name2 nickname2
name3 nickname3我希望我的程序读取该文件,并显示姓名/昵称情侣。
下面是我所做的:
users_file = fopen("users", "r");
while(!feof(users_file))
{
fscanf(users_file, "%s %s", &user.username, &user.name);
printf("%s | %s\n", user.username, user.nickname);
}下面是输出:
name1 | nickname1
name2 | nickname2
name3 | nickname3
name3 | nickname3为什么最后一个是重复的?谢谢
发布于 2012-03-09 00:10:55
您需要在fscanf()之后立即检查feof(),或者检查fscanf()本身的返回值。最后一个是重复的,因为由于到达eof,fscanf()不会将任何新数据读取到user.username和user.nickname中。
可能的修复方法:
/*
* You could check that two strings were read by fscanf() but this
* would not detect the following:
*
* name1 nickname1
* name2 nickname2
* name3 nickname3
* name4
* name5
*
* The fscanf() would read "name4" and "name5" into
* 'user.username' and 'user.name' repectively.
*
* EOF is, typically, the value -1 so this will stop
* correctly at end-of-file.
*/
while(2 == fscanf(users_file, "%s %s", &user.username, &user.name))
{
printf("%s | %s\n", user.username, user.nickname);
}或者:
/*
* This would detect EOF correctly and stop at the
* first line that did not contain two separate strings.
*/
enum { LINESIZE = 1024 };
char line[LINESIZE];
while (fgets(line, LINESIZE, users_file) &&
2 == sscanf(line, "%s %s", &user.username, &user.name))
{
printf("%s | %s\n", user.username, user.name);
}发布于 2012-03-09 00:12:14
如果您将您的循环更改为:
while((fscanf(users_file, "%s %s", &user.username, &user.name))
{
printf("%s | %s\n", user.username, user.nickname);
}然后它应该可以工作,请注意,我们不检查EOF,我们让fscanf为我们检查。
发布于 2012-03-09 00:18:13
如果看到文件结束的情况,则feof()函数将返回true。如果是从文件中读取,情况可能并非如此。
有多种方法可以绕过这一点,is的工作(实际上也是hmjd所说的)是:
while (fscanf(users_file, "%s %s", &user.username, &user.name) == 2) {
...
}fscanf的返回值是成功转换和分配的转换次数,因此如果在读取时获得EOF,这将与您预期的两个不同。
https://stackoverflow.com/questions/9620822
复制相似问题