atoi()函數和stoi()函數的作用
如果我們想要把一個string類型的字符串或者存放在一個字符數組(char*類型)中的字符串轉換為數字的話,這兩個函數將會是你的好幫手。
atoi()函數和stoi()函數的頭文件
atoi()函數和stoi()函數的頭文件都是"string"(c++)
atoi()函數參數
atoi()參數是 const char* 類型的,因此可以將一個字符數組轉換成一個數字。但是如果將一個string類型的字符串轉換成數字的話,這時我們需要先調用string類成員方法.c_str()將其轉換為const char* 類型后,再進行轉換。
還需要說的一點就是,atoi()函數的返回值為int類型,代表返回將字符串轉換后的數字。
stoi()函數參數
stoi()參數是 const string& 類型的,因此可以將一個string類型的字符串轉換成一個數字。
atoi()函數和stoi()函數的注意事項
- stoi()會做范圍檢查,默認范圍在int范圍內(因為返回的是int類型),如果超出范圍的話則會runtime error!
- atoi()則不會做范圍檢查,如果超出范圍的話,超出上界,則輸出上界,超出下界,則輸出下界。請看代碼:
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int main(){
string str = "333333333333333333";
//atoi()會返回上or下界(當轉換的數字超出int范圍時)
cout << atoi(str.c_str()) <<endl;
//stoi()返回out_of_range(超出邊界異常)
cout << stoi(str) << endl;
}
結果如下:
- atoi()和stoi()函數都是只轉換字符串的數字部分,如果遇到其它字符的話則停止轉換。請看代碼:
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int main(){
char str[] = {'1','2','a','3'};
string str1 = "12aa3";
//遇到了'a'字符,停止數字轉換
cout << atoi(str) << endl;
//遇到了'a'字符,停止數字轉換
cout << stoi(str1) << endl;
}
結果如下: