如何检查C++中的输入是否为数字

chi*_*der 25 c++

我想创建一个程序,该程序从用户接收整数输入,然后在用户根本不输入任何内容时终止(即,只需按Enter键).但是,我在验证输入时遇到了问题(确保用户输入的是整数,而不是字符串.atoi()将不起作用,因为整数输入可以超过一位数.

验证此输入的最佳方法是什么?我尝试了类似下面的内容,但我不知道如何完成它:

char input

while( cin>>input != '\n')
{
     //some way to check if input is a valid number
     while(!inputIsNumeric)
     {
         cin>>input;
     }
}
Run Code Online (Sandbox Code Playgroud)

gre*_*ade 41

cin得到输入它不能使用时,它设置failbit:

int n;
cin >> n;
if(!cin) // or if(cin.fail())
{
    // user didn't input a number
    cin.clear(); // reset failbit
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input
    // next, request user reinput
}
Run Code Online (Sandbox Code Playgroud)

当设置为cins时failbit,使用cin.clear()重置流的状态,然后cin.ignore()清除剩余的输入,然后请求用户重新输入.只要设置了故障状态并且流包含错误输入,流就会出现异常.

  • 不要忘记`.reset()`流. (3认同)
  • 这个问题(反对我对Q的阅读)是在按下<ENTER>之后它不会放弃; 相反 - `cin >> n`将继续运行,直到成功,错误或文件结束. (2认同)

Chr*_*ian 19

检查std::isdigit()功能.


Hap*_*ran 7

用法的问题

cin>>number_variable;
Run Code Online (Sandbox Code Playgroud)

当你输入123abc值时,它将通过,你的变量将包含123.

你可以使用像这样的正则表达式

double inputNumber()
{
    string str;
    regex regex_pattern("-?[0-9]+.?[0-9]+");
    do
    {
        cout << "Input a positive number: ";
        cin >> str;
    }while(!regex_match(str,regex_pattern));

    return stod(str);
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以更改regex_pattern以验证您想要的任何内容.