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.
It's been a while since I've done and C/C++, but it would appear to me that the (overly) simple solution would be to check just the string for "0".
Since this is tagged c++:
An alternative to
strtol
issscanf
, although it's a little heavy-weight:However, this allows leading whitespace in your string (which may or may not be desirable), and it allows anything to trail the number, so "123abc" would be accepted and return 123. If you want to have tighter control, go with
strtol()
, as AndreyT demonstrates.For C++11 and later:
The go-to function for string-to-integer conversion is now
stoi
, which takes astring
and returns anint
, 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
forlong
/long long
/float
/double
/long double
conversions, respectively.)From the man page for strtol():
The proper function (as long as you are insisting on using C-style functions) is
strtol
and the conversion code might look as followsSome remarks:
strtol
allows (meaning: quietly skips) whitespace in front of the actual number. If you what to treat such leading whitespace as an error, you have to check for it yourself.The check for
*end != '\0'
makes sure that there's nothing after the digits. If you want to permit other characters after the actual number (whitespace?), this check has to be modified accordingly.P.S. I added the
end == number
check later to catch empty input sequences. "All whitespace" and "no number at all" inputs would have been caught by*end != '\0'
check alone. It might make sense to catch empty input in advance though. In that caseend == number
check will/might become unnecessary.