There is strtol which is better IMO. Also I have taken a liking in strtonum, so use it if you have it (but remember it’s not portable):
long long
strtonum(const char *nptr, long long minval, long long maxval,
const char **errstr);
You might also be interested in strtoumax and strtoimax which are standard functions in C99. For example you could say:
uintmax_t num = strtoumax(s, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
/* Could not convert. */
Anyway, stay away from atoi:
The call atoi(str) shall be equivalent to:
(int) strtol(str, (char **)NULL, 10)
except that the handling of errors may differ. If the value cannot be
represented, the behavior is undefined.
Robust C89 strtol-based solution
With:
no undefined behavior (as could be had with the atoi family)
a stricter definition of integer than strtol (e.g. no leading whitespace nor trailing trash chars)
classification of the error case (e.g. to give useful error messages to users)
a “testsuite”
#include
#include
#include
#include
#include
typedef enum {
STR2INT_SUCCESS,
STR2INT_OVERFLOW,
STR2INT_UNDERFLOW,
STR2INT_INCONVERTIBLE
} str2int_errno;
/* Convert string s to int out.
*
* @param[out] out The converted int. Cannot be NULL.
*
* @param[in] s Input string to be converted.
*
* The format is the same as strtol,
* except that the following are inconvertible:
*
* – empty string
* – leading whitespace
* – any trailing characters that are not part of the number
*
* Cannot be NULL.
*
* @param[in] base Base to interpret string in. Same range as strtol (2 to 36).
*
* @return Indicates if the operation succeeded, or why it failed.
*/
str2int_errno str2int(int *out, char *s, int base) {
char *end;
if (s[0] == ‘