0

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

3
Contributors
5
Replies
6
Views
8 Years
Discussion Span
Last Post by Sh13
Featured Replies
  • 1
    Aia 1,977   8 Years Ago

    Then, the problem is that fscanf() is not been successful converting the input into floats. In fact I can see another err: [iCODE]fscanf(ifp, "%f", [COLOR="Red"]&[/COLOR]array[i].miles);[/iCODE] fscanf() needs to have an address to store the conversion, you are not giving it that by missing the [COLOR="Red"]& [/COLOR] It's always a good … Read More

  • 1

    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. Read More

0

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.

0

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

1

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.

1

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.

Comments
Thanks for the help!
0

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.
Be sure to adhere to our posting rules.