Skip to main content
5 of 9
added 16 characters in body
pellucide
  • 3.7k
  • 2
  • 24
  • 25

I like Dan's answer, 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++; } 

Added a check for other non-zero errno too.
 if (errno != 0) { return INCONVERTIBLE; } 

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; } 
pellucide
  • 3.7k
  • 2
  • 24
  • 25