我正在从文件中读取信息。该文件包含格式
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/