atoi
相同點:
①都是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;
-
}