1.基本说明
c库函数: strtol()
1.头文件
<stdlib.h>
2. 函数形式
long strtol( const char *str, char**str_end, int base);
3. 功能
字符串形式的数字转换成long整型
4. 参数
♦ str: 指向要被转译的空终止字符串的指针,合法的整数字符串由下列部分组成:
- (可选)正或负号
- (可选)指示八进制底的前缀(
0
)(仅当base为 8 或 0 时应用)- (可选)指示十六进制底的前缀(
0x
或0X
)(仅当base为 16 或 0 时应用)- 一个数字序列
♦ str_end: 指向str整数字符指针的指针,所指向的指针,指向最后被转译字符的
后一字符。若
str_endv
为 NULL ,则忽略它。
♦base: 被转译整数值的数字进制5. 返回值
若成功,则返回对应 str 内容的整数值。若被转换值落在对应返回类型的范围外,则发生值域错误(设 errno为ERANGE)
并返回 LONG_MAX 、 LONG_MIN 、 LLONG_MAX 或 LLONG_MIN 。若无法进行转换,则返回 0
2. 代码
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
int main(void)
{
// 带错误处理的剖析
const char *p = "10 200000000000000000000000000000 30 -40 junk";
printf("Parsing '%s':\n", p);
char *end;
for (long i = strtol(p, &end, 10);
p != end;
i = strtol(p, &end, 10))
{
printf("'%.*s' -> ", (int)(end-p), p);
p = end;
if (errno == ERANGE){
printf("range error, got ");
errno = 0;
}
printf("%ld\n", i);
}
// 不带错误处理的剖析
printf("\"1010\" in binary --> %ld\n", strtol("1010",NULL,2));
printf("\"12\" in octal --> %ld\n", strtol("12",NULL,8));
printf("\"A\" in hex --> %ld\n", strtol("A",NULL,16));
printf("\"junk\" in base-36 --> %ld\n", strtol("junk",NULL,36));
printf("\"012\" in auto-detected base --> %ld\n", strtol("012",NULL,0));
printf("\"0xA\" in auto-detected base --> %ld\n", strtol("0xA",NULL,0));
printf("\"junk\" in auto-detected base --> %ld\n", strtol("junk",NULL,0));
}
3.结果
xuehy@ubuntu:~/code/lib_study/lib_cpp_and_c$ make
g++ -std=c++11 -I. strtol_demo.cpp -o app
Make successfull!
xuehy@ubuntu:~/code/lib_study/lib_cpp_and_c$ ./app
Parsing '10 200000000000000000000000000000 30 -40 junk':
'10' -> 10
' 200000000000000000000000000000' -> range error, got 9223372036854775807
' 30' -> 30
' -40' -> -40
"1010" in binary --> 10
"12" in octal --> 10
"A" in hex --> 10
"junk" in base-36 --> 926192
"012" in auto-detected base --> 10
"0xA" in auto-detected base --> 10
"junk" in auto-detected base --> 0