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

时间:2011-04-13 20:23:06

标签: c++

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

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

char input

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

7 个答案:

答案 0 :(得分:38)

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
}

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

答案 1 :(得分:19)

查看std::isdigit()功能。

答案 2 :(得分:6)

使用

的问题
cin>>number_variable;

是当你输入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);
}

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

答案 3 :(得分:3)

我发现自己现在一直在使用boost::lexical_cast来做这类事情。 例如:

std::string input;
std::getline(std::cin,input);
int input_value;
try {
  input_value=boost::lexical_cast<int>(input));
} catch(boost::bad_lexical_cast &) {
  // Deal with bad input here
}

该模式也适用于您自己的类,只要它们满足一些简单的要求(必要方向的可流性,以及默认和复制构造函数)。

答案 4 :(得分:2)

为什么不使用scanf(“%i”)并检查其返回?

答案 5 :(得分:0)

我猜ctype.h是您需要查看的头文件。它有许多处理数字和字符的功能。 在这种情况下,isdigit或iswdigit会帮助你。

这是一个参考: http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/isdigit_xml.html

答案 6 :(得分:0)

如果您已经拥有该字符串,则可以使用此功能:

bool isNumber( const string& s )
{
  bool hitDecimal=0;
  for( char c : s )
  {
    if( c=='.' && !hitDecimal ) // 2 '.' in string mean invalid
      hitDecimal=1; // first hit here, we forgive and skip
    else if( !isdigit( c ) ) 
      return 0 ; // not ., not 
  }
  return 1 ;
}