函数原型
long int strtol (const char *__restrict __nptr,
char **__restrict __endptr, int __base)
功能:
strtol()函数:将一个字符串转成长整型数据并作为函数的返回值返回。
函数检测到第一个非法字符时,立即停止检测,其后的所有字符都会被当作非法字符处理。
参数解析
(1)合法字符串__restrict __nptr会被转换为long int, 作为函数的返回值。
(2)非法字符串,即从第一个非法字符的地址,被赋给*__restrict __endptr。**__restrict __endptr是个双重指针,即指针的指针。strtol()函数就是通过它改变*__restrict __endptr的值,即把第一个非法字符的地址传给__restrict __endptr。
多数情况下,传入的字符串为数据字符串,__restrict __endptr设置为NULL, 即不返回非法字符串。
(3)参数base的范围为2~36,和0;它决定了字符串以被转换为整数的权值。
即如base 值为10 则采用10 进制,若base 值为16 则采用16 进制。
如果base为0或者16,并且字符串以0x(或者0X)开头,那么,x(或者X)被忽略,字符串按16进制转化。如果base不等于0和16,并且字符串以0x(或者0X)开头,那么x被视为非法字符。
示例
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6 char buffer[30]="0x120helloworld!@123 Bye!\n";
7 char *endptr;
8
9 printf("The output of strtol is: 0x%lx \n",strtol(buffer, &endptr, 16));
10 printf("The endptr of strtol is: %s\n", endptr);
11 }
输出结果:
The output of strtol is: 0x120
The endptr of strtol is: helloworld!@123 Byte!
buff[30] ="120hellowrold!@123 Bye!"输出结果与上同。
6 char buffer[30]="120helloworld!@123 Byte!\n";
7 char *endptr;
8
9 printf("The output of strtol is: 0x%lx \n",strtol(buffer, &endptr, 10));
10 printf("The output of strtol is: %ld \n",strtol(buffer, &endptr, 10));
11 printf("The endptr of strtol is: %s\n", endptr);
输出结果:
The output of strtol is: 0x78
The output of strtol is: 120
The endptr of strtol is: helloworld!@123 Byte!