版權聲明:本文系原創,轉載請聲明出處。
1. 函數原型
int stoi (const string& str, size_t* idx = 0, int base = 10); int stoi (const wstring& str, size_t* idx = 0, int base = 10);
2. 參數說明
- str
- String object with the representation of an integral number.
- idx
-
Pointer to an object of type size_t, whose value is set by the function to position of the next character in
str after the numerical value.
This parameter can also be a null pointer, in which case it is not used.
- base
-
Numerical base (radix) that determines the valid characters and their interpretation.
If this is 0, the base used is determined by the format in the sequence (see strtol for details). Notice that by default this argument is 10, not 0.
3. 返回值
如果解析成功,返回轉換后的整數。
On success, the function returns the converted integral number as an int value.
4. 異常處理
stoi當字符串不符合規范時,會拋出異常,所以在使用stoi時應該有必要的異常處理:
#include <stdexcept> #include <iostream> #include <string> using namespace std; int main() { std::string y = "253647586946334221002101219955219971002"; int x; try { x = stoi(y); } catch (std::invalid_argument&){ // If no conversion could be performed, an invalid_argument exception is thrown. cout << "Invalid_argument" << endl; } catch (std::out_of_range&){ // If the value read is out of the range of representable values by an int, an out_of_range exception is thrown. cout << "Out of range" << endl; } catch (...) { // everything else cout << "Something else" << endl; } return 0; }
參考資料:
- https://blog.csdn.net/u014694994/article/details/79074566
- http://www.cplusplus.com/reference/string/stoi/?kw=stoi
