0

In this code snippet I try to count the number of rows contained in a file. The data are divided into seven columns and 421 rows. However, the total number outmput returns as 422, that is counted in more than one line. Why? How can I avoid this problem?

I know it's wrong to use instruction while (! Feof (inStr)), but I was asked explicitly to use it.

int valid = 0;

[...]

while(!feof(inStr)){
        fscanf(inStr," %c %f %f %f %f %f %d",&app1, &app2, &app3, &app4, &app5, &app6,&app7);
        valid++;
    }
    printf("%d",valid);
4

2 回答 2

1

问题是您需要feof在尝试之后立即进行检查fscanf,但在增加行计数器之前。否则,您将为eof.

while(1){
    fscanf(inStr," %c %f %f %f %f %f %d",&app1, &app2, &app3, &app4, &app5, &app6,&app7);
    if (feof(inStr)) break;
    valid++;
}
printf("%d",valid);

当然,您也可以按照 Martin James 的建议进行操作,然后从结果中减去一个。

于 2014-04-23T09:29:50.457 回答
0

不要循环while (!feof(...)),它不会像您期望的那样工作,因为直到您尝试从文件末尾读取之后才设置 EOF 标志。而是使用例如while (fscanf(...) == 7)(在您的特定情况下)。

使用的问题while (!feof(...))是它会循环一次到多次,这正是您遇到的问题。

于 2014-04-23T09:30:34.743 回答