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?