c++中的atoi()和stoi()函数的用法和区别
最后发布:2018-08-27 20:58:41
首发:2018-08-27 20:58:41
<div id="article_content" class="article_content clearfix" style="height: 1827px; overflow: hidden;">
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-211130ba7a.css">
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-211130ba7a.css">
<div class="htmledit_views" id="content_views">
<h3><a name="t0"></a><a name="t0"></a>相同点:</h3>
①都是C++的字符处理函数,把数字字符串转换成int输出
②头文件都是#include<cstring>
不同点:
①atoi()的参数是 const char* ,因此对于一个字符串str我们必须调用 c_str()的方法把这个string转换成 const char*类型的,而stoi()的参数是const string*,不需要转化为 const char*;
如图:
②stoi()会做范围检查,默认范围是在int的范围内的,如果超出范围的话则会runtime error!
如图:
而atoi()不会做范围检查,如果超出范围的话,超出上界,则输出上界,超出下界,则输出下界;
代码:
-
//myfirst.cpp--displays a message
-
#include "stdafx.h"
-
#include <iostream>
-
#include <set>
-
#include <string>
-
using namespace std;
-
int main()
-
{
-
string s1 = "2147482", s2 = "-214748";
-
string s3 = "214748666666663", s4 = "-21474836488";
-
cout << stoi(s1) << endl;
-
cout << stoi(s2) << endl;
-
cout << atoi(s3.c_str()) << endl;
-
cout << atoi(s4.c_str()) << endl;
-
return 0;
-
}
控制台:
<div class="person-messagebox">
<div class="left-message"><a href="https://blog.csdn.net/qq_33221533">
<img src="https://profile.csdnimg.cn/A/5/9/3_qq_33221533" class="avatar_pic" username="qq_33221533">
</a></div>
<div class="middle-message">
<div class="title"><span class="tit "><a href="https://blog.csdn.net/qq_33221533" data-report-click="{"mod":"popu_379","ab":"new"}" target="_blank">鸡啄米的时光机</a></span>
<!-- 等级,level -->
<img class="identity-icon" src="https://csdnimg.cn/identity/blog5.png"> </div>
<div class="text"><span>原创文章 102</span><span>获赞 107</span><span>访问量 25万+</span></div>
</div>
<div class="right-message">
<a class="btn btn-sm bt-button personal-watch" data-report-click="{"mod":"popu_379","ab":"new"}">关注</a>
<a href="https://im.csdn.net/im/main.html?userName=qq_33221533" target="_blank" class="btn btn-sm bt-button personal-letter">私信
</a>
</div>
</div>
</div>
</article>