As WhirlWind has pointed out, the recommendations to use atoi
aren't really very good. atoi
has no way to indicate an error, so you get the same return from atoi("0");
as you do from atoi("abc");
. The first is clearly meaningful, but the second is a clear error.
He also recommended strtol
, which is perfectly fine, if a little bit clumsy. Another possibility would be to use sscanf
, something like:
if (1==sscanf(argv[1], "%d", &temp))
// successful conversion
else
// couldn't convert input
note that strtol
does give slightly more detailed results though -- in particular, if you got an argument like 123abc
, the sscanf
call would simply say it had converted a number (123), whereas strtol
would not only tel you it had converted the number, but also a pointer to the a
(i.e., the beginning of the part it could not convert to a number).
Since you're using C++, you could also consider using boost::lexical_cast
. This is almost as simple to use as atoi
, but also provides (roughly) the same level of detail in reporting errors as strtol
. The biggest expense is that it can throw exceptions, so to use it your code has to be exception-safe. If you're writing C++, you should do that anyway, but it kind of forces the issue.