Jared Jared - 24 days ago 8
C++ Question

How do I tell if the c function atoi failed or if it was a string of zeros?

When using the function

atoi
(or
strtol
or similar functions for that matter), how can you tell if the integer conversion failed or if the C-string that was being converted was a
0
?

For what I'm doing,
0
is an acceptable value and the C-string being converted may contain any number of
0
s. It may also have leading whitespace.

Answer Source

For C++11 and later:

The go-to function for string-to-integer conversion is now stoi, which takes a string and returns an int, or throws an exception on error.

No need for the verbose istringstream hack mentioned in the accepted answer anymore.

(There's also stol/stoll/stof/stod/stold for long/long long/float/double/long double conversions, respectively.)