how to check if given c++ string or char* contains only digits?

rsk82 picture rsk82 · Jan 17, 2012 · Viewed 91.5k times · Source

Or from the other way around find first non digit character.

Do the same functions apply for string and for char* ?

Answer

Blastfurnace picture Blastfurnace · Jan 17, 2012

Of course, there are many ways to test a string for only numeric characters. Two possible methods are:

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
}