Вопрос

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);
Это было полезно?

Решение

The problem is that you need to do the feof check immediately after you try to fscanf, but before you increment your row counter. Otherwise you will increment it for the 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);

Of course, you could also do as Martin James suggested and subtract one from the result.

Другие советы

Don't loop while (!feof(...)), it will not work as you expect since the EOF flag is not set until after you try to read from beyond the end of the file. Instead use e.g. while (fscanf(...) == 7) (in your specific case).

The problem with using while (!feof(...)) is that it will loop once to many which is exactly the problem you have.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top