当我请求号码但用户输入非号码时,如何防止失控的输入循环?

Ash*_*ies 3 c++ cin

如果输入错误的类型,我需要知道如何使我的cin语句看起来不会"删除".代码在这里:

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;
}
Run Code Online (Sandbox Code Playgroud)

例如,执行,输入一个字符,它会循环不间断,就好像cin语句不存在一样.

Fre*_*urk 5

您必须检查输入是否成功并在不输入时进行处理:

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;
}
Run Code Online (Sandbox Code Playgroud)

如果不检查提取是否成功,则cin将处于失败状态(cin.fail()).一旦处于失败状态,稍后的提取将立即返回而不是尝试从流中读取,从而有效地使它们成为无操作 - 导致无限循环.