for loop reads the last number of the .txt file into the array twice

Hi guys,

I was wondering why the function that I've made below enters the last digit of the inputFile .txt file into the array time twice, when it should do this only once.

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void readFile(ifstream &inputFile, string currentFileName, double time[], int &numEntries) {

	numEntries = 0;

	for(int i = 0; i < 20; i++) {

		while(!inputFile.eof()) { 

			inputFile >> time[i];
			cout << "DERP " << time[i] << " DERP" << endl;
			numEntries++;
	
		}
		//cout << "hur" << endl;	
	}
	
	inputFile.close();

}


output:


(64): more abank.txt
Alpha Bank
4.5 5.6 4.9 7.0 4.0 5.0
3.4 5.5 6.0
4.5
(65): a.out
Greetings!
This program allows you to analyze up to 10 banks.
Enter number of banks would you like to analyze: 2
Please enter file name: abank.txt
DERP 4.5 DERP
DERP 5.6 DERP
DERP 4.9 DERP
DERP 7 DERP
DERP 4 DERP
DERP 5 DERP
DERP 3.4 DERP
DERP 5.5 DERP
DERP 6 DERP
DERP 4.5 DERP
DERP 4.5 DERP
Please enter file name: ^C
(66): 

This is only what I think happens, I don't know for certain if it's true.

So you have 10 numbers in your file. When the program reads the 10th number, it doesn't know that it is the last number in the file.

That means that the End Of File bit has not been set. The condition !inputFile.eof() is still true.

Now your loop tries to read a number into time[i] again, except this time there is nothing to read. There is no input and the eof bit is set. Since there is no input, time[i] remains the same.
This is only what I think happens, I don't know for certain if it's true.


You got it pretty much exactly.
I see. Could this be due to the fact that I have a character return after the last digit in the .txt file?
Topic archived. No new replies allowed.