Even in C, using atoi
isn't a good thing to do for converting user input. It doesn't provide error checking at all. Providing a C++ version of it wouldn't be all that useful - considering that it wouldn't throw and do anything, you can just pass .c_str()
to it and use it.
Instead you should use strtol
in C code, which does do error checking. In C++03, you can use stringstreams to do the same, but their use is error-prone: What exactly do you need to check for? .bad()
, .fail()
, or .eof()
? How do you eat up remaining whitespace? What about formatting flags? Such questions shouldn't bother the average user, that just want to convert his string. boost::lexical_cast
does do a good job, but incidentally, C++0x adds utility functions to facilitate fast and safe conversions, through C++ wrappers that can throw if conversion failed:
int stoi(const string& str, size_t *idx = 0, int base = 10);
long stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);
long long stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);
Effects: the first two functions call strtol(str.c_str(), ptr, base)
, and the last three functions
call strtoul(str.c_str(), ptr, base)
, strtoll(str.c_str(), ptr, base)
, and strtoull(str.c_str(), ptr, base)
, respectively. Each function returns the converted result, if any. The argument ptr
designates a pointer to an object internal to the function that is used to determine what to store at *idx
. If the function does not throw an exception and idx != 0
, the function stores in *idx
the index of the first unconverted element of str.
Returns: the converted result.
Throws: invalid_argument
if strtol
, strtoul
, strtoll
, or strtoull
reports that no conversion could be performed. Throws out_of_range
if the converted value is outside the range of representable values for the return type.