c库函数:strtol()使用说明

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​ 时应用)
  • (可选)指示十六进制底的前缀( 0x0X )(仅当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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青草地溪水旁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值