atoi和strtol的区别和使用

     atoi和strtol函数均是把字符串转换成整数,两者的不同点主要是:

1,atoi的返回值无法区分是正常的返回还是错误的返回,如:

      int val;

      val = atoi("abc"); 与val = atoi("0");

      两者返回的val均为0,因此无法区分哪个是正确parse后的值。

 

2,strtol函数对异常的返回可以设置errno,从而可以发现异常的返回,如:

     errno = 0;    /* To distinguish success/failure after call */
     val = strtol(str, &endptr, base);

 

     /* Check for various possible errors */

     if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
                   || (errno != 0 && val == 0)) {
         perror("strtol");
         exit(EXIT_FAILURE);
     }

    

3,strtol函数支持不同进制的转换,而atoi只支持十进制的转换。

     函数原型说明:

     #include <stdlib.h>

     int atoi(const char *nptr);

 

     #include <stdlib.h>
     long int
     strtol(const char *nptr, char **endptr, int base);

 

4,下面给出linux man strtol 的 demo 代码:

[cpp]  view plain copy
  1. #include <stdlib.h>  
  2. #include <limits.h>  
  3. #include <stdio.h>  
  4. #include <errno.h>  
  5.   
  6. int main(int argc, char *argv[]) {  
  7.    int base;  
  8.    char *endptr, *str;  
  9.    long val;  
  10.   
  11.    if (argc < 2) {  
  12.        fprintf(stderr, "Usage: %s str [base]/n", argv[0]);  
  13.        exit(EXIT_FAILURE);  
  14.    }  
  15.   
  16.    str = argv[1];  
  17.    base = (argc > 2) ? atoi(argv[2]) : 10;  
  18.   
  19.    /* To distinguish success/failure after call */  
  20.    errno = 0;      
  21.    val = strtol(str, &endptr, base);  
  22.   
  23.    /* Check for various possible errors */  
  24.    if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 && val == 0)) {  
  25.        perror("strtol");  
  26.        exit(EXIT_FAILURE);  
  27.    }  
  28.   
  29.    if (endptr == str) {  
  30.        fprintf(stderr, "No digits were found/n");  
  31.        exit(EXIT_FAILURE);  
  32.    }  
  33.   
  34.   /* If we got here, strtol() successfully parsed  
  35.     a number */  
  36.   
  37.    printf("strtol() returned %ld/n", val);  
  38.    /* Not necessarily an error... */  
  39.    if (*endptr != '/0')      
  40.   printf("Further characters after number: %s/n", endptr);  
  41.    exit(EXIT_SUCCESS);  
  42.  }  

转自: atoi和strtol的区别和使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值