Monday, 21 November 2016

c - How to read numbers from file and calculate the mean?

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...