I have a file which I am reading using ifstream
. This file contains 26 numbers separated by whitespace ranging from 0 - 25; "21 1 24 16 10 6 14 3 0 18 20 9 4 19 2 25 7 12 5 11 15 17 8 13 23 22
". I am streaming them into my program using the stream::operator >>
.
In the code snippet below, I get stuck in an infinite loop. Preceding this code snippet, the following occur:
file
is used to read through the file mentioned above, and successfully reaches the end of the file. Strangely, the file is read in in the same manner - usingwhile( !file.eof () )
and storing the read values in anint
.- After this,
file.clear;
andfile.seekg(0);
are called to clear theEOF
flag and move the stream to the start again. The
file
ifstream is then passed by reference into a function, where it is also calledfile
. It is in this function where the code snippet below is executed.while( !file.eof() ){ file >> intFromFile; if( counter < 26 ){ contacts[counter] = intFromFile; if( repeatValue( contacts, intFromFile, counter )){ return true; } } if( counter == 26 && file.eof() ){ file.close(); return false; } counter++; }
Here I end up in an infinite loop, where counter
continues to increment, and
I never reach the end of the file. I'm unsure how this occurs, if the same framework worked before successfully. The eof flag is never raised.
Although, I am not sure why this happens.
If I cout << intFromFile;
I get all the numbers in the file printed as expected,
"21 1 24 16 10 6 14 3 0 18 20 9 4 19 2 25 7 12 5 11 15 17 8 13 23 22
". However, after 22
which is the last number in the file, the loop keeps reading in 0
, and never ending. Why is this? The file (to my knowledge) not been changed since the previous read mentioned in 1. .
Any help would be greatly appreciated.