You are not actually reading 3
twice.
The problem is that after the last number (3
), there are other characters, namely whitespaces. So, the EOF flag is not raised after reading the last number and your while
loop enters another iteration. No value is read by fscanf
, but the previous one is still in tmp
, which gets processed again.
What you should do, is check the return value of fscanf
, which will tell you the number of parameters actually scanned and converted. It should be 1
, because you are trying to scan one variable. Fix your code like:
while(!feof(f))
{
if (fscanf(f, "%lf", &tmp) != 1) {
// No numbers
break;
}
printf("tmp = %f \n", tmp);
sum += tmp;
++ i;
}
and remove the i = i - 1
. You had to write it to compensate the fact that loop was iterating one more time than intended.
No comments:
Post a Comment