过滤掉无效的用户输入 [英] Filtering out invalid user inputs

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

问题描述

我正在尝试使用以下代码块在小型C ++程序中过滤掉无效的用户输入:

I'm trying to filter out invalid user inputs in a small C++ program using the following chunk of code:

    int selection = -1;
    while (!(selection >= 1 && selection <=4))
    {   
        cin >> selection;

        if (!(selection >= 1 && selection <=4))
        {
            cout << "invalid selection!" << endl;
            cout << "selection: ";
        }
    }

输入数字值似乎效果很好在我要过滤的范围之内或之外。但是,当我输入无效值(例如,大于最大可存储int或字符的值)时,会发生奇怪的事情。代码循环并跳过 cin命令。

It seems to work fine when I enter any numerical value that is either inside or outside the range i want to filter. However strange things happen when I enter invalid values such as values larger than the maximum storable int or characters. The code loops through and skipping the "cin" command.

如何解决此问题?

谢谢

推荐答案

您需要使用 fail()检测不可转换的输入,然后忽略其余的错误数据,并在读取新的输入尝试之前使用 clear()重置 cin 错误标志。

You need to detect unconvertible input using fail() and then ignore the rest of the bad data and reset cin error flags using clear() before reading in a new input attempt.

int selection = -1;
while (!(selection >= 1 && selection <=4))
{   
    cin >> selection;

    if (cin.fail() || !(selection >= 1 && selection <=4))
    {
        cout << "invalid selection!" << endl;
        cout << "selection: ";

        cin.clear();

        cin.ignore(std::numeric_limits<int>::max(), '\n');
    }
}

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

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