首页 > 解决方案 > Wrong type of input

问题描述

I have the code below, so basically my problem is: when someone input a character like 'a', it will pop a message that requires a re-input

I tried using the ASCII: if (a >= 97 && a <= 122) but it still didn't work

double a;
cin >> a;
if (a >= 'a' && a <= 'z')
    {
        cout << "Wrong input, please re-input a:  " << endl;
        cin >> a;
    }
cout << a;

I expect it to pop the message to re-input but the actual output is always 0 no matter what character I input

标签: c++

解决方案


可以通过在条件中直接使用流来检查流的状态。如果一切正常,它“返回”真,否则“假”。所以你可以做例如

if (!(cin >> a))
{
    // Invalid input, or other error
}

在无效输入上,您需要清除状态。

请注意,如果输入无效,则不会读取输入,并且下次尝试读取时,您将读取与第一次失败完全相同的输入。解决它的一种方法是忽略该行的其余部分。另一种是将整行读入一个字符串,然后将其放入输入字符串流中以解析输入。


推荐阅读