C函数strtol

函数定义

long int strtol(const char *nptr,char **endptr,int base);

函数说明

参数base范围从2至36,或0。参数base代表采用的进制方式,如base值为10则采用10进制,若base值为16则采用16进制等。当base值为0时则是采用10进制做转换,但遇到如’0x’前置字符则会使用16进制做转换、遇到’0’前置字符而不是’0x’的时候会使用8进制做转换。


一开始strtol()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,再遇到非数字或字符串结束时(’\0’)结束转换,并将转换数值返回。参数endptr指向停止转换的位置,若字符串nptr的所有字符都成功转换成数字则endptr指向串结束符’\0’。判断是否转换成功,应检查**endptr是否为’\0’。

举例

#include<stdlib.h>
#include<stdio.h>
int main()
{
    char *string, *stopstring;
    double x;
    int base;
    long l;
    unsigned long ul;
    string = "3.1415926 This stopped it";
    x = strtod(string, &stopstring);
    printf("string = %s\n", string);
    printf("strtod = %f\n", x);
    printf("Stopped scan at: %s\n", stopstring);
    string = "-1011 This stopped it";
    l = strtol(string, &stopstring, 10);
    printf("string = %s\n", string);
    printf("strtol = %ld\n", l);
    printf("Stopped scan at: %s\n", stopstring);
    string = "10110134932";
    printf("string = %s\n", string);
    /*Convertstringusingbase2,4,and8:*/
    for(base = 2; base <= 8; base *= 2)
    {
        /*Convertthestring:*/
        ul = strtoul(string, &stopstring, base);
        printf("strtol = %ld(base %d)\n", ul, base);
        printf("Stopped scan at: %s\n", stopstring);
    }
    return 0;
}

输出结果:

string = 3.1415926 This stopped it
strtod = 3.141593
Stopped scan at:  This stopped it
string = -1011 This stopped it
strtol = -1011
Stopped scan at:  This stopped it
string = 10110134932
strtol = 45(base 2)
Stopped scan at: 34932
strtol = 4423(base 4)
Stopped scan at: 4932
strtol = 2134108(base 8)
Stopped scan at: 932
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值