# file stream looping like crazy

## Recommended Posts

Lets say I have a text file with this line: 646; now heres some code:
while (!inFile.eof())
{
int number;
inFile >> number;
float erraticBehavior;
inFile >> erraticBehavior;
}


this causes an endless loop.....why? I'm guessing the reason is that maybe the semicolon after the 646 is only 1 byte and i'm asking for a float value, which is more than 1 byte. That seems to be the case but I would expect that I would just get a wierd or undefined value for the float as opposed to the program deciding to just endlessly loop. Thanks for any replies

##### Share on other sites
Brother Bob    10344
You ask for an integer, so it reads 646. Then you ask for a float, but there's no valid floating point number in the stream, so it stops and sets either the fail bit or the bad bit (don't know which) and leaves the semicolon in the stream.

End of file is not reached, so loop again. Read an integer, but stream is not in a valid state (fail or bad bit set) so don't read anything. Then read a float, but still not a valid state.

End of file not reached, to loop again. Read an integer, but not a valid stream state. And so on...

##### Share on other sites
Aardvajk    13207
When you try to read the ; as a float, the stream fails. The ; is left in the input stream and the eof state never gets reached.

If you check for stream.fail() after reading, that will detect it and you can break out of the loop, or repair or whatever.

##### Share on other sites
by the way, how do i add in that "SOLVED" thing?....or is that something a moderator does?

##### Share on other sites
Brother Bob    10344
Clicky. In other words; don't do it.

##### Share on other sites
Zahlman    1682
Don't do that ("Doctor, it hurts..."). Generally, prefer to do things something like this:

int number;float erraticBehavior;while (inFile >> number >> erraticBehavior) {}

See here for more.