gpt4 book ai didi

c - 在C中读取文件中的名称

转载 作者:太空狗 更新时间:2023-10-29 15:33:28 26 4
gpt4 key购买 nike

我有这样一个文件:

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

为什么最后一个重复了?谢谢

最佳答案

您需要在 fscanf() 之后立即检查 feof(),或者检查 fscanf() 的返回值本身。重复最后一个是因为 fscanf() 由于达到 eof 而没有将任何新数据读入 user.usernameuser.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);
}

关于c - 在C中读取文件中的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9620822/

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