The program I am making is supposed to read in numbers from a text file and save the total number of numbers, the average value of the numbers in a struct.
I have a stru
If you see a reference of fscanf, you will see that it returns the number of items successfully scanned, and not the value you just scanned.
That means you have to check differently for your ending condition.
You also should not loop while (!feof(...))
, as the end-of-file condition will not be set until you already tried to read beyond the end of the file.
Instead you could do something like this:
while (fscanf(tsin, " %f", &in_last) > 0)
{
if (in_last == 0.0f)
++x;
else
{
/* The rest of your code */
}
}
This will read until you reach end-of-file, or there is an error, and increase the index once you read 0.0
. The leading space in the fscanf
format string make fscanf
skip whitespace (spaces, tabs, newlines).
There are also a couple of other problems with your code. For example, you donät update the average
variable. The value of serie[x].totnr
may not be initialized, and so increasing it (and using it in operations in general) will in that case be undefined as well. And then you use sizeof(series)
which will not work, as series
is not actually an array in the function but a pointer, so the sizeof
operator returns the size of the pointer and not the number of entries in the array. Instead return x
which is now the size of the array.