繁体   English   中英

如何在不退出do while循环的情况下验证输入?

[英]How do I validate input without exiting my do while loop?

我正在开发一个程序,该程序通过输入1-3(退出4)来提示用户从3个不同的选项中进行选择。 我需要编写一个代码来验证输入是否为整数,如果不是整数则重新提示它们。 这是我的代码的基本思想(整个发布太久了)。

do 
{
cout << "Menu: Please select one of the following options:" << endl;
    cout << " 1 - Drop a single chip into one slot." << endl;
    cout << " 2 - Drop multiple chips into one slot." << endl;
    cout << " 3 - Drop 5 chips into each slot." << endl;
    cout << " 4 - Quit the program." << endl;
    cout << "Enter your selection now: ";
    cin >> first_input;
}while (first_input!=4)

然后,我有多个if语句根据用户选择的选项执行表达式。 我还将提示他们稍后在代码中输入其他整数值。

如果用户输入未能输入整数而是输入字符,如何将用户送回菜单? 约束:不能使用continuebreak

提前致谢。

如果您想重新开始使用非整数输入,也许像这样的事情行得通吗?

// Insert after "cin >> first_input;"
if (cin.fail()) {
    // Handle non-int value.

    // Clear error flag.
    cin.clear();

    // Empty buffer up to next newline.
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    // Complain & restart.
    cout << "Invalid input.  Please try again." << endl;
    continue;
}

这样做是清除错误标志,清除缓冲区,然后重新开始。 cin.ignore()不需要显式地传递std::numeric_limits<std::streamsize>::max()作为其第一个参数; 但是,如果出现错误,我更愿意这样做,以确保错误的输入消失了。 请注意, std::numeric_limits是在标准头文件<limits>定义的,并且需要将其包括在内。

您正在寻找continue关键字。

do 
{
    cout << "Menu: Please select one of the following options:" << endl;
    cout << " 1 - Drop a single chip into one slot." << endl;
    cout << " 2 - Drop multiple chips into one slot." << endl;
    cout << " 3 - Drop 5 chips into each slot." << endl;
    cout << " 4 - Quit the program." << endl;
    cout << "Enter your selection now: ";
    cin >> first_input;
    //lets say if user enters value out of range. then want to show menu again.
    if(first_input > 4) {
        cout << "Invalid input "<<endl;
        continue;
    }
    // you can do other stuff here. 
    // ...
}while (first_input!=4)

您可以尝试使用goto标签。

 do{ label: // your code if(check) goto label; }while(check); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM