tags:

views:

86

answers:

1

I don't understand, why cin >> W; in step 3 is omitted, if i input not a number (i.e. 's').

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
  short W = -1;

  cout << "step 1) W = " << W << endl;
  cout << "give a number: ";
  cin >> W;

  if ( cin.fail() )
  {
    cout << "ERROR, bad number" << endl;
    W = -1;

    cout << endl << "step 2) W == " << W << endl;
    cin.clear();
  }

  cout << endl << "step 3) W == " << W << endl;
  cout << "give a number: ";
  cin >> W;

  cout << endl << "step 4) W == " << W << endl;

  system("PAUSE");
  return EXIT_SUCCESS;
}
+2  A: 

I'm assuming, you are puzzled by the case where you enter a non-number for step 1 and then the step 3 seems not to work.

The problem is, that cin.clear() clears only the error flags of the stream. The wrong input is not taken out of the stream, so the next cin >> W just reads the same wrong input again.

You can for example fill a string from cin which takes everything or you can use cin.ignore() to ignore the following characters in the input stream.

See http://www.arachnoid.com/cpptutor/student1.html for a more detailed explanation.

Steffen
the problem is that i've tried to put one / two `cin.ignore();` inside if block, and it seems it doesn't work .. that's why i am confused about 'how it really works'
dygi
ok, i got it, `cin.clear();` have to be **BEFORE** 'cin.ignore();` not after .. thank you for the link .. now i understand what does mean 'broken stream' .. now, the post can be CLOSED
dygi