1

I'm using the fscanf() function to read through a text file which looks like this:

d 5.234 f
a 4.234 b
d 53.5 c
...

and so on. I want to sum up the values in the middle column, but only in the rows where the first letter is d and the second is f. My code looks like this:

FILE *p;
char x[2], z[2];
float y, sum=0;
p=fopen("file.txt", "r");
if(p==NULL) return 1;

while(!feof(p))
{   fscanf(p, "%s %f %s", &x, &y, &z);
    if (x[0]=='d' && z[0]=='f') sum+=y;
}

and it works fine - as long as x and z are arrays. If I declare them as single characters, then tell the fscanf() to scan for such (%c), for some reason it runs through the last row of the file twice. Thus, if the last row meets the requirements, the sum is greater than it ought to be. Can anybody tell what's the difference?

Raccoon
  • 13
  • 3
  • 1
    `%s` will skip leading whitespace characters including newline. `%c` does not. So `%c` will store the newline into one of your variables. – kaylum Feb 20 '17 at 23:36
  • Read [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – BLUEPIXY Feb 20 '17 at 23:39
  • 1
    1) "then tell the fscanf() to scan for such (%c)" --> post the code that does this. You statement has many potential implementations, best to see exactly what you want. 2) Having trouble with input? Check the return value of `fscanf()` is a good first step. – chux - Reinstate Monica Feb 20 '17 at 23:40
  • The answer below helped. Thanks anyway, I'm going to read about feof() some more. – Raccoon Feb 20 '17 at 23:54

1 Answers1

0

Your error is feof().

It triggers if the last operation caused an EOF. With %s, this will happen the matcher will continue reading until it hits EOF. With %c it wont. The next call to fscanf() then fails, but you don't check that.

  while(!feof(fp))
  {
      /* read from fp */
  }

is a common anti-pattern or error.

Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18