How do I prevent a runaway input loop when I request a number but the user enters a non-number?

前端 未结 6 824
名媛妹妹
名媛妹妹 2020-12-11 09:03

I need to know how to make my cin statement not appear to \'remove\' itself if you input the wrong type. The code is here:

int mathOperator()
{
  using names         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 09:43

    You must check that input succeeded and handle when it doesn't:

    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;
    }
    

    If you don't check that extraction succeeded, then cin is left in a failed state (cin.fail()). Once in a failed state, later extractions will immediately return instead of trying to read from the stream, effectively making them no-ops – leading to your infinite loop.

提交回复
热议问题