如何在c++中检查输入是否为数字

时间:2020-12-29 00:06:30

I want to create a program that takes in integer input from the user and then terminates when the user doesn't enter anything at all (ie, just presses enter). However, I'm having trouble validating the input (making sure that the user is inputting integers, not strings. atoi() won't work, since the integer inputs can be more than one digit.

我想创建一个程序,该程序接受用户的整数输入,然后在用户什么都不输入时终止(例如,按enter)。但是,我在验证输入时遇到了麻烦(确保用户输入的是整数而不是字符串)。atoi()不会起作用,因为整数输入可以超过一个数字。

What is the best way of validating this input? I tried something like the following, but I'm not sure how to complete it:

验证输入的最佳方式是什么?我试过以下方法,但我不知道如何完成:

char input

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

7 个解决方案

#1


34  

When cin gets input it can't use, it sets failbit:

当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
}

When cin's failbit is set, use cin.clear() to reset the state of the stream, then cin.ignore() to expunge the remaining input, and then request that the user re-input. The stream will misbehave so long as the failure state is set and the stream contains bad input.

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

#2


17  

Check out std::isdigit() function.

看看std::isdigit()函数。

#3


5  

The problem with the usage of

使用的问题

cin>>number_variable;

is that when you input 123abc value, it will pass and your variable will contain 123.

当您输入123abc值时,它将通过,而您的变量将包含123。

You can use regex, something like this

可以使用regex,类似这样

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);
}

Or you can change the regex_pattern to validate anything that you would like.

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

#4


3  

I find myself using boost::lexical_cast for this sort of thing all the time these days. Example:

我发现自己一直在使用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
}

The pattern works just as well for your own classes too, provided they meet some simple requirements (streamability in the necessary direction, and default and copy constructors).

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

#5


2  

Why not just using scanf("%i") and check its return?

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

#6


0  

I guess ctype.h is the header file that you need to look at. it has numerous functions for handling digits as well as characters. isdigit or iswdigit is something that will help you in this case.

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

Here is a reference: http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/isdigit_xml.html

这里有一个参考:http://docs.portcadero.com/products/rad_studio/delphiandcpp2009/helpupdate2/en/html/devwin32/isdigit_xml.html。

#7


0  

If you already have the string, you can use this function:

如果你已经有了这个字符串,你可以使用这个函数:

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 ;
}

#1


34  

When cin gets input it can't use, it sets failbit:

当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
}

When cin's failbit is set, use cin.clear() to reset the state of the stream, then cin.ignore() to expunge the remaining input, and then request that the user re-input. The stream will misbehave so long as the failure state is set and the stream contains bad input.

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

#2


17  

Check out std::isdigit() function.

看看std::isdigit()函数。

#3


5  

The problem with the usage of

使用的问题

cin>>number_variable;

is that when you input 123abc value, it will pass and your variable will contain 123.

当您输入123abc值时,它将通过,而您的变量将包含123。

You can use regex, something like this

可以使用regex,类似这样

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);
}

Or you can change the regex_pattern to validate anything that you would like.

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

#4


3  

I find myself using boost::lexical_cast for this sort of thing all the time these days. Example:

我发现自己一直在使用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
}

The pattern works just as well for your own classes too, provided they meet some simple requirements (streamability in the necessary direction, and default and copy constructors).

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

#5


2  

Why not just using scanf("%i") and check its return?

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

#6


0  

I guess ctype.h is the header file that you need to look at. it has numerous functions for handling digits as well as characters. isdigit or iswdigit is something that will help you in this case.

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

Here is a reference: http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/isdigit_xml.html

这里有一个参考:http://docs.portcadero.com/products/rad_studio/delphiandcpp2009/helpupdate2/en/html/devwin32/isdigit_xml.html。

#7


0  

If you already have the string, you can use this function:

如果你已经有了这个字符串,你可以使用这个函数:

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 ;
}