(!inFile.eof()) not reading last line?

So, I've been going at this all morning (just to let the people here know that I'm not one to just look for the answers an not do assignments myself).

I'm basically trying to make a simple program that reads integers out of a text file and only adds the positive ones and not the negatives.

All is well except it won't take the last integer (the last line, I presume.)
I took the negative out, nothing to do with that. I put more numbers in and I made the txt file less, no answer. No matter what the last number is, the program won't read it. I've been researching online and I've been seeing that it might be an issue with "while "!inFile.eof())".

Anyway here's the program:
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
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
	ifstream inFile;
	ofstream outFile;

	int total = 0;
	int inputVal,throwaway = 0;

	inFile.open("data.txt");

	outFile.open("out.txt");

	inFile >> inputVal;

	while (!inFile.eof())
	{
		 
		 if (inputVal <= 0)
		 {
		 inputVal += throwaway;
		 }

		 else
	     total += inputVal;
		 inFile >> inputVal;
		
	}

	cout << "The total is: "<< total << endl;
	outFile << "The total is: "<< total << endl;
		
		inFile.close();
	outFile.close();

	return 0;

}


Here's the txt file:
5
6
-9
21
3

I'm always getting 32 for some reason.
One must remember that one can reach the end of file on an input extraction that went perfectly well. Don't test against eof unless that is actually what you're wanting to test against.

Changing line 19 to:

while (inFile)

should be enough to fix your issue.
Thank you so much. Working now!
Topic archived. No new replies allowed.