Or from the other way around find first non digit character.
Do the same functions apply for string and for char* ?
You can use the isdigit() macro to check if a character is a number. Using this, you can easily write a function that checks a string for containing numbers only.
Use the test() method to check if a string contains only digits, e.g. /^[0-9]+$/. test(str) . The test method will return true if the string contains only digits and false otherwise.
The function isdigit() is used to check that character is a numeric character or not. This function is declared in “ctype. h” header file. It returns an integer value, if the argument is a digit otherwise, it returns zero.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With