Alternative to atoi()
there is better way with using strtol()
:
Defined in header <stdlib.h>
long strtol( const char *str, char **str_end, int base ); (until C99)
long strtol( const char *restrict str, char **restrict str_end, int base ); (since C99)
long long strtoll( const char *restrict str, char **restrict str_end, int base ); (since C99)
The call atoi(str)
shall be equivalent to: (int) strtol(str, (char **)NULL, 10)
except that the handling of errors may differ.
For atoi()
, if the value cannot be represented(not in the format below), the behavior is undefined.
- (optional) plus or minus sign
- (optional) prefix (0) indicating octal base (applies only when the base is 8 or 0)
- (optional) prefix (0x or 0X) indicating hexadecimal base (applies only when the base is 16 or 0)
- a sequence of digits
For If the str is empty or does not have the expected form, no conversion is performed, and (if str\_end
is not NULL) the value of str is stored in the object pointed to by str_end.
See ref: