By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,948 Members | 663 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,948 IT Pros & Developers. It's quick & easy.

abnormaL BEHAVIOUR ?

P: 9
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2.  
  3.  using namespace std;
  4.  
  5.  
  6.  int main()
  7.  {
  8.  
  9.      int x;
  10.  
  11.      while(1)
  12.      {
  13.  
  14.         cout << "enter the x value : \n";
  15.         cin >> x;
  16.  
  17.        if(cin.good()) 
  18.        {
  19.          cout<< "x is a integer = " << x << endl;
  20.          break;
  21.        }
  22.  
  23.        cin.clear();
  24.  
  25.      }
  26.  
  27.      return 0;
  28.  
  29.  }
  30.  
when i give this set of input,

case 1:

i/p = 12

x is a integer = 12.

case 2:

i/p = 12.34

x is a integer = 12.

case 3:

i/p = qwer

it is running in infinite loop....
it is not asking for another input..

why ?
Jun 15 '07 #1
Share this Question
Share on Google+
2 Replies


P: 79
It's this statement

Expand|Select|Wrap|Line Numbers
  1.        if(cin.good()) 
  2.        {
  3.          cout<< "x is a integer = " << x << endl;
  4.          break;
  5.        }
If you type some text instead of a number, cin.good() will return false, which means you will never go into that loop.

The only break statement you have in the while loop is in that if statement. So if you don't go in it, you will never break, meaning you will stay in the loop forever.
Jun 15 '07 #2

weaknessforcats
Expert Mod 5K+
P: 9,197
I woudl also like to add that doing a clear() just resets the failbit but the character that caused the trouble is still in the input stream.

You may want to do a cin.ignore() to eat that character. That is, if it is appropriate in your design.
Jun 15 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.