c++ 判断字符串是否为数字

#include "stdafx.h"
#include <Regex>
#include 
#include 

int _tmain(int argc, _TCHAR* argv[])
{
    std::string str ("123441115111111");
    std::regex rx("[0-9]+");
    bool bl = std::regex_match(str.begin(),str.end(), rx);
    
        
    if (bl)
        std::cout << "the string is all numbers" << std::endl;
    else
        std::cout << "the string contains non numbers" << std::endl;

        getchar();

        return 0;

另外,其实除了用正则表达式外,你也可以通过其他方式来实现这个要求。例如:

bool is_digits(const std::string &str)
{
    return str.find_first_not_of("0123456789") == std::string::npos;
}

or

bool is_digits(const std::string &str)
{
    return std::all_of(str.begin(), str.end(), ::isdigit); // C++11
}

你可能感兴趣的:(c++)