I am writing a program where I add a unknown amount of integers from a file. They must be separated between even and odd. When I run the code, my evenIntegersSum adds an extra iteration, (ie should be 20 and not 24). The input is:
1 2 1 2 2 2 1 1 2 2 3 4 4
While the output is:
The sum of the even integers is: 24
The sum of the odd integers is: 7
But should read:
The sum of the even integers is: 20
The sum of the odd integers is: 7
I would imagine that the file contains a space or other non-numeric characters past the last number. This makes the loop execute one more time (because inData.eof() is not true yet). At this point, I am guessing that operator>> is failing, and this leaves the variable 'number' untouched. Since you don't perform error checking, your code simply assumes there is one more number to process.
Sooooo, to correct, I guess you can do:
1 2 3 4 5 6 7
while (!inData.eof())
{
inData >> number;
if (inData.fail()) continue;
//Add the rest of the loop here.
....
}
Did not test so all this is theoretically. Test yourself.