atoi、stoi和strtol的使用

本文详细介绍了C++中三种不同的字符串转整型的方法:atoi、stoi 和 strtol。通过具体的示例代码展示了每种方法的特点及使用场景,包括如何处理溢出、非法字符等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

来源 :https://blog.youkuaiyun.com/godop/article/details/79600923

1、atoi

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

[html]  view plain  copy
  1. #include<iostream>  
  2. #include<cstdlib>  
  3. #include<string>  
  4. using namespace std;  
  5. void atoiInt1(){  
  6.     string s="111111";  
  7.     cout<<atoi(s.c_str())<<endl;  
  8. }  
  9. void atoiInt2(){  
  10.     string s="111nnn1111";  
  11.     cout<<atoi(s.c_str())<<endl;  
  12. }  
  13. void atoiInt3(){  
  14.     string s="2147483648";  
  15.     cout<<atoi(s.c_str())<<endl;  
  16. }  
  17. int main(){  
  18.     atoiInt1();  
  19.     atoiInt2();  
  20.     atoiInt3();  
  21.     return 0;  
  22. }   

输出:

111111
111
-2147483648

2、stoi

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

[html]  view plain  copy
  1. #include<iostream>  
  2. #include<cstdlib>  
  3. #include<string>  
  4. using namespace std;  
  5. int stoiInt1(){  
  6.     string s="111111";  
  7.     cout<<stoi(s.c_str())<<endl;  
  8. }  
  9. int stoiInt2(){  
  10.     string s="111nnn1111";  
  11.     cout<<stoi(s.c_str())<<endl;  
  12. }  
  13. int stoiInt3(){  
  14.     string s="2147483648";  
  15.     cout<<stoi(s.c_str())<<endl;  
  16. }  
  17. int main(){  
  18.     stoiInt1();  
  19.     stoiInt2();  
  20.     stoiInt3();  
  21.     return 0;  
  22. }   

输出:

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

3、strtol

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

[html]  view plain  copy
  1. #include<iostream>  
  2. #include<cstdlib>  
  3. #include<string>  
  4. using namespace std;  
  5. int strtolInt1(){  
  6.     string s="111111";  
  7.     cout<<strtol(s.c_str(),nullptr,2)<<endl;  
  8. }  
  9. int strtolInt2(){  
  10.     string s="111nnn1111";  
  11.     cout<<strtol(s.c_str(),nullptr,10)<<endl;  
  12. }  
  13. int strtolInt3(){  
  14.     string s="21474836482";  
  15.     cout<<strtol(s.c_str(),nullptr,10)<<endl;  
  16. }  
  17. int strtolInt4(){  
  18.     string s="-21474836482";  
  19.     cout<<strtol(s.c_str(),nullptr,10)<<endl;  
  20. }  
  21. int main(){  
  22.     strtolInt1();  
  23.     strtolInt2();  
  24.     strtolInt3();  
  25.     strtolInt4();  
  26.     return 0;  
  27. }  

输出:

63
111
2147483647
-2147483648

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值