atoi和strtol函数均是把字符串转换成整数,两者的不同点主要是:
1,atoi的返回值无法区分是正常的返回还是错误的返回,如:
int val;
val = atoi("abc"); 与val = atoi("0");
两者返回的val均为0,因此无法区分哪个是正确parse后的值。
2,strtol函数对异常的返回可以设置errno,从而可以发现异常的返回,如:
errno = 0; /* To distinguish success/failure after call */
val = strtol(str, &endptr, base);
/* Check for various possible errors */
if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
|| (errno != 0 && val == 0)) {
perror("strtol");
exit(EXIT_FAILURE);
}
3,strtol函数支持不同进制的转换,而atoi只支持十进制的转换。
函数原型说明:
#include <stdlib.h>
int atoi(const char *nptr);
#include <stdlib.h>
long int
strtol(const char *nptr, char **endptr, int base);
4,下面给出linux man strtol 的 demo 代码:
#include <stdlib.h> #include <limits.h> #include <stdio.h> #include <errno.h> int main(int argc, char *argv[]) { int base; char *endptr, *str; long val; if (argc < 2) { fprintf(stderr, "Usage: %s str [base]/n", argv[0]); exit(EXIT_FAILURE); } str = argv[1]; base = (argc > 2) ? atoi(argv[2]) : 10; /* To distinguish success/failure after call */ errno = 0; val = strtol(str, &endptr, base); /* Check for various possible errors */ if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 && val == 0)) { perror("strtol"); exit(EXIT_FAILURE); } if (endptr == str) { fprintf(stderr, "No digits were found/n"); exit(EXIT_FAILURE); } /* If we got here, strtol() successfully parsed a number */ printf("strtol() returned %ld/n", val); /* Not necessarily an error... */ if (*endptr != '/0') printf("Further characters after number: %s/n", endptr); exit(EXIT_SUCCESS); }