strtol 字符数组,转数值


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


    首先,说atol。

    这个函数定义为:

  1. long atol(const char* s);  
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. }  
#include<iostream>
#include<string>

using namespace std; 

int main()
{
	char a[] = "123"; 
	cout<<atoi(a)<<endl; 

	char b[] = "abc"; 
	cout<<atoi(b)<<endl; 

	char c[] = "23&"; 
	cout<<atoi(c)<<endl; 
	
	string str = "234"; 
	cout<<atoi(str.c_str())<<endl; 

	return 0; 
}

结果:



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

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


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

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


    再说strtol函数。

函数定义为:

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


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

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



    有下面几个例子:





所以说,strtol函数中的输入base的作用还是挺大的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值