首页 > 编程语言 > 详细

C++ atoi()和stoi()的区别

时间:2019-09-07 13:43:06      阅读:102      评论:0      收藏:0      [点我收藏+]

头文件都是#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;
}

 

技术分享图片

 

C++ atoi()和stoi()的区别

原文:https://www.cnblogs.com/Bella2017/p/11480317.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!