What\'s the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of returning zero).
I like Dan Moulding's answer, I'll just add a bit of C++ style to it:
#include
#include
#include
#include
int to_int(const std::string &s, int base = 0)
{
char *end;
errno = 0;
long result = std::strtol(s.c_str(), &end, base);
if (errno == ERANGE || result > INT_MAX || result < INT_MIN)
throw std::out_of_range("toint: string is out of range");
if (s.length() == 0 || *end != '\0')
throw std::invalid_argument("toint: invalid string");
return result;
}
It works for both std::string and const char* through the implicit conversion. It's also useful for base conversion, e.g. all to_int("0x7b")
and to_int("0173")
and to_int("01111011", 2)
and to_int("0000007B", 16)
and to_int("11120", 3)
and to_int("3L", 34);
would return 123.
Unlike std::stoi
it works in pre-C++11. Also unlike std::stoi
, boost::lexical_cast
and stringstream
it throws exceptions for weird strings like "123hohoho".
NB: This function tolerates leading spaces but not trailing spaces, i.e. to_int(" 123")
returns 123 while to_int("123 ")
throws exception. Make sure this is acceptable for your use case or adjust the code.
Such function could be part of STL...