c++ - 验证输入

标签 c++ validation input

cin >> menuChoice;

while (!(cin >> menuChoice))
 {
   cout << "invalid selection, please enter a number from the menu  1" << endl;
   cin.clear();
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
 }

我想“捕获”一个字符串,这样程序就不会崩溃或进入连续循环,所以我进入了上面的 while 循环。看起来不错。直到我在菜单选择中输入 0 - !(cin >> menuChoice) 被调用,即使它是有效输入(我将使用另一个循环来确保它在范围内,但只要它是一个 int 就应该没问题,这就是我的想法。

我什至尝试过

if (menuChoice == 0)
   menuchoice = 6;

就在 while 循环之前,但无济于事。

有什么帮助吗?

最佳答案

我希望将菜单和验证部分分开(目前它的功能,但我会在未来将它们更改为类)。

验证部分:

while (!(cin >> menuChoice))
{
   cout << "invalid selection, please enter a number from the menu  1" << endl;
   cin.clear();
   cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

while (menuChoice < 1 || menuChoice > 4)
{
    cout << "invalid selection, please enter a number from the menu  2" << endl;
    cin >> menuChoice;  //here is where there is a problem

    while (!(cin >> menuChoice))
    {
        cout << "invalid selection, please enter a number from the menu 3" << endl;
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

}

while 循环 1 - 捕获任何初始字符串输入 while 循环 2 - 确保正确的范围 while 循环 3 - 捕获用户可能第二次输入的任何字符串输入

关于c++ - 验证输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26285232/

相关文章:

css - 将输入占位符颜色更改为更深

c++ - 阻塞套接字性能与非阻塞套接字

c++ - 在库中使用模板

C++ 错误 : Class has-a-relationship with Struct in Same Header File

jquery - 让 MVC 4 验证 jquery Accordion 表单的所有部分

html - 如何隐藏 &lt;input type ='file' > 中的文件位置?

javascript - 防止将错误的值粘贴到输入数字类型中

c++ - 指向函数的模板指针的部分模板特化

javascript - 为什么这个 "IF"即使条件为假也总是执行?

c# - 数据注释/验证和动态值