I am trying to add values that I read from input file using fscanf. There are 15 float values that were read from .txt file.
Im copying some of the code here

#define MAX 15

for (i = 0; i < MAX; i++)
fscanf(ifp, "%f", array[i].miles);

Then I have to add up those 15 float values and store it in some variable.
Im trying to use for loop here

int miles;

for (i = 0; i < MAX; i++)
miles += array[i];

This wont store those 15 float value in miles. When I print miles, I get garbage value not added figure.
Just need some hint on this

9 Years
Discussion Span
Last Post by Sh13

Did you initialized miles before starting to add to it?

Funny part: fscanf(ifp, "%f", array[i].miles); array.miles is the field of a structure array element. miles += array[i]; array is an element of an array, hopefully float or double.


Yes I have initialized

float miles;

sorry I was trying to do

miles += array[i].miles;

under for loop

And yes, I read data from input file and stored it in array of structure


Then, the problem is that fscanf() is not been successful converting the input into floats.
In fact I can see another err: fscanf(ifp, "%f", &array[i].miles); fscanf() needs to have an address to store the conversion, you are not giving it that by missing the &
It's always a good practice to check the return of functions.
This is the return for it:
On success, the function returns the number of items succesfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure.
In the case of an input failure before any data could be successfully read, EOF is returned.


another thing, "miles" needs to be initialized to zero before you start iteratively adding values into it.

just declaring it as a float does not initialize it.

Votes + Comments
Thanks for the help!

Thank you both. It worked after I initialized miles to 0.
Too bad, I couldn't use it in my assignment because it was due at mid night.
I did it the long way. But It'll help me in the future.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.