Sign in to follow this  

file stream looping like crazy

This topic is 4041 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4041 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this