There are two or maybe three issues with the way you read the file.
If this is the actual contents of the file,
low high rain
30 60 0.3
25 55 0
30 65 0
|
then the first issue is the header text, "low high rain". If that is really part of the file, then you need to read past that before commencing to read the numeric data. Either use getline() to read it into a string or use
ignore()
to read and ignore up to the first newline character.
After that, variable rain is of type
int
but the data value on the first row is
0.3
. What happens here? Well, rain will contain the value 0, and the rest of the value, ".3" will remain in the buffer. On the next iteration, "." is not a valid character for
int low
so the read fails, and the fail() flag is set, no more input after that. So change the type of variable rain to
double
.
Finally, what happens when the last line of the file is reached? Well, if there is a trailing newline or any whitespace after the last value, the read will succeed, and the
fin.good()
condition will remain
true
, so one more iteration of the loop takes place.
In order to fix that, put the
fin >>
operation inside the
while
condition.
Something like this:
1 2 3 4 5 6 7 8 9
|
fin.ignore(1000, '\n'); // ignore header line
while( fin >> low >> high >> rain)
{
sumLow += low;
sumHigh += high;
sumRain += rain;
++numDays;
}
|