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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5655142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:36:57  来源:igfitidea点击:

How to check if input is numeric in C++

c++

提问by chimeracoder

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

回答by greyfade

When cingets 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 failbitis 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'sfailbit被设置时,用于cin.clear()重置流的状态,然后cin.ignore()清除剩余的输入,然后请求用户重新输入。只要设置了失败状态并且流包含错误输入,流就会行为不端。

回答by Christian

Check out std::isdigit()function.

检出std::isdigit()功能。

回答by HappyTran

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

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

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 以验证您想要的任何内容。

回答by timday

I find myself using boost::lexical_castfor 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).

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

回答by Valentin Galea

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

为什么不直接使用scanf("%i") 并检查它的返回值?

回答by Pruthvid

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.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/isdigit_xml.html

回答by bobobobo

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