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
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.)