C++ C++;“1”号班轮;由数字组成的字符串;

C++ C++;“1”号班轮;由数字组成的字符串;,c++,c++11,C++,C++11,我正在寻找一个简短(快速)的代码来检查字符串是否只包含数字,特别是寻找一行。这是我的临时代码: bool IsNumber(const std::string& str) { int i = 0; for( ; i<str.size() && isdigit(str[i]); ++i); return ( i == str.size() ); } bool-IsNumber(const-std::string&str) { int i=0

我正在寻找一个简短(快速)的代码来检查字符串是否只包含数字,特别是寻找一行。这是我的临时代码:

bool IsNumber(const std::string& str)
{
    int i = 0;
    for( ; i<str.size() && isdigit(str[i]); ++i);

    return ( i == str.size() );
}
bool-IsNumber(const-std::string&str)
{
int i=0;
对于(;i与
isdigit
一起使用:

#include <algorithm>
#include <cctype>
//..
bool allDigits = (!str.empty() && std::all_of(str.begin(), str.end(), ::isdigit));
#包括
#包括
//..
bool allDigits=(!str.empty()&&std::all_of(str.begin(),str.end(),::isdigit));
编辑:添加了空字符串的检查。

isdigit一起使用:

#include <algorithm>
#include <cctype>
//..
bool allDigits = (!str.empty() && std::all_of(str.begin(), str.end(), ::isdigit));
#包括
#包括
//..
bool allDigits=(!str.empty()&&std::all_of(str.begin(),str.end(),::isdigit));

编辑:添加了检查空字符串。

如果字符串为空怎么办?@ChristianHackl-
std::all_of
返回
true
的空范围。@AlexZywicki——最好先检查空字符串。这样,如果字符串为空,
&
就会短路,而不是进入
std::all_of
>。不幸的是,为了便于移植并避免未定义的行为,您需要将
isdigit
的参数强制转换为
unsigned char
,这将需要添加lambda并使此代码更加丑陋。@RustyX这不是由于性能。在逻辑上,对于空集,谓词对其所有元素都有效总是正确的ents:看到了。如果字符串为空怎么办?@ChristianHackl-
std::all_of
返回
true
的空范围。@AlexZywicki——最好先检查空字符串。这样,如果字符串为空,
&
就会短路,而不是进入
std::all_of
。不幸的是,为了得到por表并避免未定义的行为,您需要将
isdigit
的参数强制转换为
unsigned char
,这将需要添加lambda并使此代码更难看。@RustyX这不是由于性能。在逻辑中,对于空集,谓词对其所有元素都有效总是正确的:请参阅。我想回答这个问题is was closed
std::cout我想回答is closed
std::cout