atoi、stoi和strtol的使用

1、atoi

    将string字符串转换为int类型,只能转换为十进制;atoi函数不会对string字符串进行范围检查[-2147483648,2147483647],超过这个界限,不会报错,只会进行相应的转换,遇到非法字符会停止,不会报错;头文件为cstdlib

#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
void atoiInt1(){
	string s="111111";
	cout<<atoi(s.c_str())<<endl;
}
void atoiInt2(){
	string s="111nnn1111";
	cout<<atoi(s.c_str())<<endl;
}
void atoiInt3(){
	string s="2147483648";
	cout<<atoi(s.c_str())<<endl;
}
int main(){
	atoiInt1();
	atoiInt2();
	atoiInt3();
	return 0;
} 

输出:

111111
111
-2147483648

2、stoi

        将string字符串转换为int类型,只能转换为十进制;atoi函数会对字符串进行检查,如果超过范围,会报错,遇到非法字符同样会停下来,不会报错;头文件为string

#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
int stoiInt1(){
	string s="111111";
	cout<<stoi(s.c_str())<<endl;
}
int stoiInt2(){
	string s="111nnn1111";
	cout<<stoi(s.c_str())<<endl;
}
int stoiInt3(){
	string s="2147483648";
	cout<<stoi(s.c_str())<<endl;
}
int main(){
	stoiInt1();
	stoiInt2();
	stoiInt3();
	return 0;
} 

输出:

111111
111
terminate called after throwing an instance of 'std::out_of_range'

3、strtol

        同样是将string字符串转换为int类型,但这个函数可以自定义转换的string字符串的类型(第三个参数可定义string字符串的类型),strtol超过int范围,不会报错,只会输出最大或者最小值[-2147483648,2147483647],遇到非法字符,则同样停止,不会报错;

#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
int strtolInt1(){
	string s="111111";
	cout<<strtol(s.c_str(),nullptr,2)<<endl;
}
int strtolInt2(){
	string s="111nnn1111";
	cout<<strtol(s.c_str(),nullptr,10)<<endl;
}
int strtolInt3(){
	string s="21474836482";
	cout<<strtol(s.c_str(),nullptr,10)<<endl;
}
int strtolInt4(){
	string s="-21474836482";
	cout<<strtol(s.c_str(),nullptr,10)<<endl;
}
int main(){
	strtolInt1();
	strtolInt2();
	strtolInt3();
	strtolInt4();
	return 0;
}

输出:

63
111
2147483647
-2147483648

  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值