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
thanks

Recommended Answers

All 5 Replies

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.

commented: Thanks for the help! +1

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.