smilingbuddha
smilingbuddha

Reputation: 14670

Behaviour of std::cin when used in while loop condition C++

Here is a small contrived program which prints the integer just typed to the screen.

#include <iostream>
int main(int argc, char *argv[])
{
  int n;
  while(std::cin>>n)
    {
      std::cout<<"You typed "<<n<<std::endl;
    } 

  return 0;
}

Now when I enter integers the program works normally. However, if I enter floating point numbers like 10.8 the program displays 10 to the screen (as it should, since it is casting the floating point number to an integer), and then the program exits. Why is this happening? Given below is a sample terminal output.

Desktop: ./a.out
4
You typed 4
-9
You typed -9
10.8
You typed 10
Desktop: 

Upvotes: 2

Views: 1014

Answers (2)

user1084944
user1084944

Reputation:

After "You typed 10" line, the characters ".8" remain in the stream. When it tries to read that into an integer, it fails, and so it puts the stream into a bad state.

Since the stream is in a bad state, your loop condition fails and you fall out of the loop.

(Specifically, it sets the "bad" bit, I think, but it's been too long since I dealt with that and I'm not sure -- check the documentation if you need that level of detail)

Aside: be aware if you tried to read again, the characters ".8" would still remain in the stream, and you would fail again. This is a common I/O error.

Upvotes: 5

Keith
Keith

Reputation: 6834

There is not supposed to be any casting.

The 10.8 is read as 10, and then the . causes a failure to interpret the text as an integer, resulting in failbit being set. This in turn will cause your loop to exit.

If you wish to handle the 10.8, read in double, and do the casting yourself.

Upvotes: 5

Related Questions