c++;检查输入是否为数字 我使用Nebide IDE进行C++学习 我想强制用户只选择1到3之间的数字 int displayMenu() { while(true) { cout<<"Please choose one of following options"<<endl; cout<<"1. deposit"<<endl; cout<<"2. withdraw"<<endl; cout<<"3. exit"<<endl; int input; cin >>input; if(input>=1 && input<=3 && cin) { return input; break; } else { cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl; } } } int显示菜单() { while(true) { cout

c++;检查输入是否为数字 我使用Nebide IDE进行C++学习 我想强制用户只选择1到3之间的数字 int displayMenu() { while(true) { cout<<"Please choose one of following options"<<endl; cout<<"1. deposit"<<endl; cout<<"2. withdraw"<<endl; cout<<"3. exit"<<endl; int input; cin >>input; if(input>=1 && input<=3 && cin) { return input; break; } else { cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl; } } } int显示菜单() { while(true) { cout,c++,C++,当您尝试读取一个整数,但传递其他内容时,读取失败,流无效。导致错误的任何原因都保留在流中。这将导致无限循环 要解决此问题,请清除错误标志并忽略else子句中的其余行: else { cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl; cin.clear(); // remove error flags // skip until th

当您尝试读取一个整数,但传递其他内容时,读取失败,流无效。导致错误的任何原因都保留在流中。这将导致无限循环

要解决此问题,请清除错误标志并忽略else子句中的其余行:

    else
    {
        cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl;
        cin.clear(); // remove error flags
        // skip until the end of the line
        // #include <limits> for std::numeric_limits
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
else
{

cout您可以这样修改它:

int displayMenu()
{
    while(true)
    {  
        cout<<"Please choose one of following options"<<endl;
        cout<<"1. deposit"<<endl;
        cout<<"2. withdraw"<<endl;
        cout<<"3. exit"<<endl;
        char input = cin.get();  //read a character

        cin.ignore(numeric_limits<streamsize>::max(), '\n');  //skip the rest of characters in cin buffer so that even if a user puts "123" only the first one is taken into account

        if(input>='1' && input<='3' && cin)  //check whether this is '1', '2' or '3'
        {
            return input;
            break;
        }
        else
        {
            cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl;
        }
    }
}
int显示菜单()
{
while(true)
{  

您是否需要添加isdigit检查更好地使用
std::numeric\u limits::max()
而不是该神奇数字。256没有足够数量的跳过字符。这是正确的。使用
cin.ignore(numeric\u limits::max(),'\n')完全gonzo几乎不会丢失任何内容
请记住
#包括
@user4581301谢谢,答案已经确定了;)