eof() Getting Inproper Coding

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

Code is reproduced below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* 
   For: Chapter 5, Program CPP5_6
   Date: 06/08/11
   Saved as: CPP5_6.cpp
   Output Summary: Adds Even and Odd Numbers
*/

#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

int main()
{
    //Declare Stream Variables
	ifstream inData;
	ofstream outData;
	//Declare Variables
	int number;
	int evenNumberSum;
	int oddNumberSum;
	//Open New Data
	inData.open("CPP5_6_IntegersList.txt");
	outData.open("CPP5_6_IntegersList_Echo.txt");
	evenNumberSum = 0;
	oddNumberSum = 0;
	//Find Odd + Even Integers and Add
	while (!inData.eof())
	{
		inData >> number;
		if (number % 2 != 0)		
			oddNumberSum = oddNumberSum + number;
		
		else		
			evenNumberSum = evenNumberSum + number;		
	}
	//Output Integers
	outData << "The sum of the even integers is: " << evenNumberSum << endl;
	outData << "The sum of the odd integers is: " << oddNumberSum << endl;
	//Hold Screen
	cout << endl;
	system("pause");
	return 0;
}


	


Any help would be great. Thanks!
Last edited on
Don't loop on eof(); loop on good() instead. eof() is only false after you have tried and failed to read from the file.
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.
Thanks so much for the help!
Topic archived. No new replies allowed.