有一个文件 a.txt 看起来像这样:
1 abc
2
3 jkl
我想将该文件的每一行作为一个 int
和一个字符串来读取,如下所示:
fp = fopen("a.txt", "r");
while (1) {
int num;
char str[10];
int ret =fscanf(fp, "%d%s", &num, str);
if (EOF == ret)
break;
else if (2 != ret)
continue;
// do something with num and str
}
但是有一个问题,如果a.txt中的一行只包含一个数字,没有字符串(就像第2行),那么上面的代码就会卡在那一行。
那么有什么方法可以跳到下一行吗?
最佳答案
分两步进行:
- 使用
fgets()
读取整行。这假定您可以对要支持的线路长度设置一个简单的静态限制,但这种情况经常发生。 - 使用
sscanf()
检查和解析行。
这可以解决您遇到的问题,并且通常是解决此类问题的更好方法。
更新:正在尝试回复您的评论。在我看来,最简单的方法是始终读取整行(如上所述),然后解析出您认为它包含的两个字段:数字和字符串。
如果您使用 sscanf()
执行此操作,您可以使用返回值来确定它是如何进行的,就像您在代码中尝试使用 fscanf()
一样:
const int num_fields = sscanf(line, "%d %s", &num, str);
if( num_fields == 1 )
; /* we got only the number */
else if( num_fields == 2 )
; /* we got both the number and the string */
else
; /* failed to get either */
不确定您什么时候“不需要”该字符串;它要么存在,要么不存在。
关于c - 使用 fscanf 读取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14496596/