strtol() 字符串转长整型

函数原型 

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!
 


    

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值