如何创建一个循环,让用户在出现 cin.fail() 时重新输入他们的答案?

How do I create a loop that lets the user re-enter their answer when a cin.fail() occurs?

我程序的这一小段似乎引起了一些问题:

cout << "Would you like to change the values? Type 1 if yes or 2 if no." << endl << "You can also reverse the original vector above by typing 3. \n Answer:  ";
    cin >> yesorno;

    while (yesorno != 1 && yesorno != 2 && yesorno != 3 || cin.fail() )
        {           
        cout << "\n Sorry, didn't catch that. Try again: ";
        cin >> yesorno;
        }

据我所知,该循环对所有有效整数都能正常工作,但是当向 yesorno 声明无效值时,循环就会崩溃。例如,如果我输入字母 A,循环会一直进行到无穷大。 我想我要问的是,我该怎么做才能让用户有无限的机会输入有效值? 顺便说一句,我是 C++ 的新手,所以我不熟悉所有不同类型的 public 成员函数等。我已经尝试过 cin.clear() 但没有取得太大成功

设置 fail 位后,您需要先清除它,然后再继续。

while (yesorno != 1 && yesorno != 2 && yesorno != 3 || cin.fail() )
{           
        if ( cin.fail() ) {
                cin.clear();
                cin.ignore( std::numeric_limits<std::streamsize>::max() );
        }
        cout << "\n Sorry, didn't catch that. Try again: ";
        cin >> yesorno;
}

当您 运行 在读取输入数据时出错,您可以使用 cin.clear() to clear the state of the stream and follow it with a call to cin.ignore() 忽略该行的其余部分。

while ( (yesorno != 1 && yesorno != 2 && yesorno != 3) || cin.fail() )
{           
   cout << "\n Sorry, didn't catch that. Try again: ";
   if ( cin.fail() )
   {
      cin.clear();
      cin.input.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
   }

   cin >> yesorno;
}

我更喜欢的另一种方法是逐行读取输入并独立处理每一行。

std::string line;
while ( getline(cin, line) )
{
   std::istringstr str(line);
   if ( !(str >> yesorno) || (yesorno != 1 && yesorno != 2 && yesorno != 3) )
   {
      cout << "\n Sorry, didn't catch that. Try again: ";
      continue;
   }
   else
   {
      // Got good input. Break out of the loop.
      break;
   }
}