I like [Dan's answer][1], esp because of the avoidance of exceptions. For embedded systems development and other low level system development, there may not be a proper Exception framework available.
Added a check for white-space after a valid string...these three lines
while (isspace(*end)) {
end++;
}
<br>
Added a check for parsing errors too.
if ((errno != 0) || (s == end)) {
return INCONVERTIBLE;
}
<br>
Here is the complete function..
#include <cstdlib>
#include <cerrno>
#include <climits>
#include <stdexcept>
enum STR2INT_ERROR { SUCCESS, OVERFLOW, UNDERFLOW, INCONVERTIBLE };
STR2INT_ERROR str2long (long &l, char const *s, int base = 0)
{
char *end;
errno = 0;
l = strtol(s, &end, base);
if ((errno == ERANGE && l == LONG_MAX) || l > LONG_MAX) {
return OVERFLOW;
}
if ((errno == ERANGE && l == LONG_MIN) || l < LONG_MIN) {
return UNDERFLOW;
}
if ((errno != 0) || (s == end)) {
return INCONVERTIBLE;
}
while (isspace((unsigned char)*end)) {
end++;
}
if (*s == '\0' || *end != '\0') {
return INCONVERTIBLE;
}
return SUCCESS;
}
[1]: http://stackoverflow.com/a/6154614/892771