验证输入 [英] Validating input

查看:114
本文介绍了验证输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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它应该是罚款,这就是我的想法。

I want to 'catch' a string so that the programme doesn't crash or go into a continuous loop so I entered the above while loop. Looks good. That is until I entered 0 into menu choice - the !(cin >> menuChoice) gets called even though it is valid input (I'll use another loop to ensure it is within range but as long as it's an int it should be fine, that's what I thought.

我甚至尝试了一个

if (menuChoice == 0)
   menuchoice = 6;

无效。

任何帮助?

推荐答案

保持菜单和验证部分分离(在其功能的时刻,但我将在以后将它们改变为类)。

I'm looking to keep the menu and the validation part separate (at the moment its functions but I'll be changing them in the future to classes).

验证部分: / p>

The validation part goes:

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 - 捕获任何字符串输入用户可能第二次输入

while loop 1 - catches any initial string input while loop 2 - ensures correct range while loop 3 - catches any string input the user may enter a second time

这篇关于验证输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆