虽然不断重复字母而不是字母

son*_*ool 3 c++ if-statement while-loop

我在这里有一个while循环,只有1和2作为数字,如果我插入和数字不是这些我的其他声明将继续要求正确的一个,这是正常的.但如果我插入一封信,我的其他声明将永远循环.我怎样才能解决这个问题?

#include <iostream>
using namespace std;

int main()
{
int myChoice;
cin >> myChoice;

while ( myChoice >= 2 ||  myChoice <= 1)
{
    if (myChoice == 1)
    {
        cout <<"food1";
        break;
    }
    else if (myChoice == 2)
    {
        cout <<"food2";
        break;
    }
    else
    {
        cout << " " << endl;
        cout << "Please select the proper choices" << endl;
        cout << "Try again: ";
        cin >> myChoice;
    }
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)

ybu*_*ill 5

如果输入非数字,则cin >> myChoice失败.这意味着它在输入缓冲区中保持输入完整,当你再次到达那里时它会尝试解析它并失败,依此类推......你必须清除错误状态并忽略非数字.最简单的方法是这样的:

cout << "Try again: ";
cin.clear(); // clear error state
cin.ignore(std::numeric_limits<streamsize>::max(), '\n'); // ignore till the end of line
cin >> myChoice;
Run Code Online (Sandbox Code Playgroud)