How to prevent runaway input loop when I request a number but the user enters no number?

I need to know how to make my cin statement not display itself if you enter the wrong type. The code is here:

int mathOperator()
{
  using namespace std;

  int Input;
  do
  {
    cout << "Choose: ";
    el();
    cout << "1) Addition";
    el();
    cout << "2) Subtraction";
    el();
    cout << "3) Multiplication";
    el();
    cout << "4) Division";
    el();
    el();
    cin >> Input;

  }
  while (Input != 1 && Input != 2 && Input!=3 && Input!=4);
  return Input;
}

Execute, enter, for example, a character, and it will work without stopping, as if the cin instruction was not.

+3
source share
6 answers

After reading in a bad value, cin is in a failed state. You must reset it.

You must clear the error flag and free the buffer. In this way:

   cin.clear(); 
   cin.ignore(std::numeric_limits<streamsize>::max(), '\n');

The second call will flush the input buffer of any data that might be there to prepare you for the next cin call.

, " ", .

   inline void reset( std::istream & is )
   {
       is.clear();
       is.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
   }

istream, cin, - . , , .

+2

, , :

int mathOperator() {
  using namespace std;

  int Input;
  do {
    cout << "Choose: ";
    el();
    cout << "1) Addition";
    el();
    cout << "2) Subtraction";
    el();
    cout << "3) Multiplication";
    el();
    cout << "4) Division";
    el();
    el();
    while (!(cin >> Input)) {  // failed to extract
      if (cin.eof()) {  // testing eof() *after* failure detected
        throw std::runtime_error("unexpected EOF on stdin");
      }
      cin.clear();  // clear stream state
      cin.ignore(INT_MAX, '\n');  // ignore rest of line
      cout << "Input error.  Try again!\n";
    }
  } while (Input != 1 && Input != 2 && Input!=3 && Input!=4);
  return Input;
}

, , cin (cin.fail()). - , , , , -ops - .

+5

, , operator>> .

std::getline, std::istringstream . , / , () .

+3
char Input;

 do
 {
// same code 
 }
 while (Input != '1' && Input != '2' && Input != '3' && Input!='4');
 return Input;

[EDIT]

char int,

int i = (Input - 48);
+2

int, char, cin

+2

, char , int, , , cin int, char, , , , "".

: . Narue http://www.daniweb.com/forums/thread11505.html

0

Source: https://habr.com/ru/post/1789283/


All Articles