atol和strtol的区别

    

    字符串中有两个重要的函数:atol和strtol,它们的功能都是字符数组,转数值。但是用法差异较大。我们下面来说一下这两个函数在具体使用的时候要注意哪些方面。


    首先,说atol。

    这个函数定义为:

  1. long atol(const char* s);  

    就是输入一个字符数组(注意,不是string类型的字符串)的头元素的地址,然后我们就可以转换成数值。举个例子:


  1. #include<iostream>  
  2. #include<string>  
  3.   
  4. using namespace std;   
  5.   
  6. int main()  
  7. {  
  8.     char a[] = "123";   
  9.     cout<<atoi(a)<<endl;   
  10.   
  11.     char b[] = "abc";   
  12.     cout<<atoi(b)<<endl;   
  13.   
  14.     char c[] = "23&";   
  15.     cout<<atoi(c)<<endl;   
  16.       
  17.     string str = "234";   
  18.     cout<<atoi(str.c_str())<<endl;   
  19.   
  20.     return 0;   
  21. }  

结果:

atol和strtol的区别


如果我们输入的是第一个字符就是非法的字符,那么返回的是0;

如果我们输入的是前面是有效的数值字符,那么返回前面的数值,后面非法的不返还。


那么如果我们需要用string类型过来操作呢?可以这样子:

我们使用str.c_str()函数。


    再说strtol函数。

函数定义为:

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


    作用就是将字符串转换成长整数,base为进制数。如果转换成功,*endptr指向s; 否则*endptr指向第一个非法字符。

    关于其中的base,规定如下:

atol和strtol的区别


    有下面几个例子:


atol和strtol的区别

atol和strtol的区别

相关文章:

  • 2021-06-08
  • 2021-12-21
  • 2022-12-23
  • 2022-01-26
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-16
  • 2021-10-04
  • 2021-09-07
  • 2021-05-21
  • 2021-06-19
  • 2021-09-22
  • 2021-05-23
相关资源
相似解决方案