我想编写一个小程序来从给定的 .csv/.txt 文件中读取行并根据用户输入打印出特定的详细信息。
我目前正在与一个
FILE *input = fopen("Example.csv", "r");
输入看起来像这样:
Test000, 40, 0, empty
Test001, 0, -41, empty
现在,如果我尝试从输入到 fscanf(),它只会设置第一个 char[] 并忽略其他变量。
我的 fscanf() 调用如下所示:
fscanf(input, "%s , %d , %d , %s", name, &timeA, &timeB, info);
# I'm calling fscanf(...) inside of while()-condition.
# while (fscanf(...) == 4) { *apply logic here* }
因此,使用这段代码,fscanf() 只会将名称设置为“Test000”,然后是“40”、“0”、“empty”等,但会忽略 timeA、timeB、和信息。
它们被定义为:
char name[51];
int timeA = 0;
int timeB = 0;
char info[51];
我真的不知道如何规避这个问题。任何形式的帮助将不胜感激!
感谢您的宝贵时间。
最佳答案
可以使用扫描集。 %50[^,]
将读取最多 50 个字符或一个逗号。
fscanf(input, " %50[^,], %d , %d , %50s", name, &timeA, &timeB, info);
注意 &50[^,]
之前的空格以占用前导空格。
检查 fscanf
的返回。在这种情况下,如果成功扫描所有四个项目,将返回 4。
关于c - 从输入文件中读取字符串/单词和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51944870/