.eof is not terminating loop


I can't get the .eof() function to work. It seems that it will not break the loop. It tries to read after end of file and crashes due to arbitrary values.
1
2
3
4
5
6
7
8
9
10
11
12
while(!dataFile.eof() ){
	dataFile >> INPUT1;
	dataFile >> INPUT2;
	bigIntSum = INPUT1 * INPUT2;
	outFile << bigIntSum;
	outFile << endl;
	dataFile >> INPUT3;
	dataFile >> INPUT4;
	bigIntSum = INPUT3 * INPUT4;
	outFile << bigIntSum;
	outFile << endl;
	}
Last edited on
That's because you should be checking for EOF between lines 2 and 3.

You must attempt to read past EOF before it is testable.
So should I create an if statement to test for end of file between those two line. I am going to try that right now.
Oh I think I got it. I created a do/while loop. Also, if you are still there I have another question.
Yes, you've got it.

File operations are typically abstracted away into a function. For example:

1
2
3
4
5
6
7
8
9
10
11
12
struct point
  {
  int x, y;
  point( int x = 0, int y = 0 ): x( x ), y( y ) { }
  };

istream& operator >> ( istream& ins, point& pt )
  {
  ins >> pt.x;
  ins >> pt.y;
  return ins;
  }
1
2
3
point INPUT1;
vector <point> plot;
while (dataFile >> INPUT1) plot.push_back( INPUT1 );

Glad to help.
Topic archived. No new replies allowed.