If you want to check if string contains only a number and nothing (except spaces), use this:
#include <sstream> bool is_numeric (const std::string& str) { std::istringstream ss(str); double dbl; ss >> dbl; // try to read the number ss >> std::ws; // eat whitespace after number if (!ss.fail() && ss.eof()) { return true; // is-a-number } else { return false; // not-a-number } }
ss >> std::ws important for accepting numbers with a trailing space, for example "24 " .
The ss.eof() check is important for rejecting strings such as "24 abc" . This ensures that we reach the end of the line after reading the number (and spaces).
Wiring harness:
#include <iostream> #include <iomanip> int main() { std::string tests[8] = { "", "XYZ", "a26", "3.3a", "42 a", "764", " 132.0", "930 " }; std::string is_a[2] = { "not a number", "is a number" }; for (size_t i = 0; i < sizeof(tests)/sizeof(std::string); ++i) { std::cout << std::setw(8) << "'" + tests[i] + "'" << ": "; std::cout << is_a [is_numeric (tests[i])] << std::endl; } }
Output:
'': not a number 'XYZ': not a number 'a26': not a number '3.3a': not a number '42 a': not a number '764': is a number ' 132.0': is a number '930 ': is a number
Quasar donkey
source share