天天看點

數字字元串轉換為數字:stoi()和atoi()

相同點:

①都是C++的字元處理函數,把數字字元串轉換成int輸出

②頭檔案都是#include

不同點:

①atoi()的參數是 const char* ,是以對于一個字元串str我們必須調用 c_str()的方法把這個string轉換成 const char類型的,而stoi()的參數是const string&,不需要轉化為 const char;

②stoi()會做範圍檢查,預設範圍是在int的範圍内的,如果超出範圍的話則會runtime error!而atoi()不會做範圍檢查,如果超出範圍的話,超出上界,則輸出上界,超出下界,則輸出下界;

// include <string>

double stod(const string& _Str, size_t *_Idx = nullptr);
float stof(const string& _Str, size_t *_Idx = nullptr);
int stoi(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
long stol(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
long double stold(const string& _Str, size_t *_Idx = nullptr);
unsigned long stoul(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
long long stoll(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);
unsigned long long stoull(const string& _Str, size_t *_Idx = nullptr, int _Base = 10);      
stoi()函數如果傳入的字元串s中含有不是數字的字元,則隻會識别到從開頭到第一個非法字元之前,如果第一個字元就是非法字元則會報錯