c - 为什么出现错误后无法使用 fscanf 读取?

标签 c scanf

我正在从文件中读取信息。该文件包含格式

5
3 4 5 6
5 6 a 8 9 2
3 9 42 51 32
67 53 43
5 6 7 8 9 2

第 1 行包含测试用例数量 N 接下来的 N 行将包含由空格分隔的整数。 现在我想要的输出是

18
Invalid Input
137
163
37

对于每个测试用例,输出由一个对应于加法的整数组成。 我已经给出了代码

#include <stdio.h>
#include <stdlib.h>

int main()
{
   FILE *fp;
   int flag=0,total=0,r=0,n,i,value,x;
   char filename[100],c;
   scanf("%s",filename);
   fp=fopen(filename,"r");
   fscanf(fp,"%d",&n);
   for(i=1;i<=n;i++)
   {
       total=0;
       flag=0;
       do
    {
        r=fscanf(fp,"%d%c",&value,&c);
        if(r!=2)
        {
            printf("\nInvalid Input");
            flag=1;
            break;
        }
        else
            total+=value;
    }while(c!='\n');
    if(flag!=1)
    {
       printf("\n%d",total);
    }
}
}

但是由于我们在错误后无法使用 fscanf 读取,因此我无法读取整个输入。并且我正在获取输出

18
Invalid Input
Invalid Input
Invalid Input
Invalid Input

那么我该怎么做才能获得所需的输出

最佳答案

scanf 到达包含无效字符 'a' 的位置时,它会尝试使用 %d 格式说明符读取它。由于这不起作用,scanf'a' 保留在缓冲区中,并返回 0 作为从输入读取的项目数。

由于您的代码尝试再次读取 %d,所以什么也没有发生:缓冲区保持在读取之前的位置,'a' 作为下一个字符。这将持续到计数 n 耗尽为止。

通过添加从输入读取的代码来修复此问题,直到退出内循环后到达 '\n'EOF:

do {
    ... // This is your reading loop
} while (c != '\n');
// We can reach this line either because `c` is `'\n'`, or because of an error
// If we are here due to an error, read until the next `'\n'`
while (c != '\n') {
    if (fscanf(fp, "%c", &c) == 0) {
        break; // We are at the end of file
    }
}

关于c - 为什么出现错误后无法使用 fscanf 读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37860190/

相关文章:

c - 是否可以将 C 文件编译为 .app 而不是 .exe 文件?

c - 为 C 字符串编写正则表达式

c - 为什么循环后有一个换行符

c - 在 C 中使用 fscanf 扫描字符串

c - 如何获得某些 Visual Basic 6 控件的 IUnknown* 指针(如果有)?

c - 处理导致段错误的空字符串输入

c - 双指针运算,遍历数组字符串的字符

c - 使用 %c 或 %s 扫描

c++ - 使用 fscanf 从文件中读取字符

c - 为什么 scanf() 会导致此代码中的无限循环?