long int strtol(const char *nptr, char **endptr, int base);
strtol是atoi的增强版,参数base范围从2至36,或0。参数base代表采用的进制方式,0/10是十进制
1. endptr是一个传出参数,函数返回时指向后面未被识别的第一个字符。例如char *pos; strtol("123abc", &pos, 10);
strtol返回123,pos指向字符串中的字母a。
2. 如果字符串开头没有可识别的整数,例如char *pos; strtol("ABCabc", &pos, 10);
则strtol返回0,pos指向字符串开头,可以据此判断这种出错的情况,而这是atoi处理不了的
/* strtol example */
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
int main ()
{
char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
char * pEnd;
long int li1, li2, li3, li4;
li1 = strtol (szNumbers,&pEnd,10);
li2 = strtol (pEnd,&pEnd,16);
li3 = strtol (pEnd,&pEnd,2);
li4 = strtol (pEnd,NULL,0);
printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);
return 0;
}
Output:
The decimal equivalents are: 2001, 6340800, -3624224 and 7340031