一、定義及參數介紹
- int stoi (const string& str, size_t* idx = 0, int base = 10);
- int stoi (const wstring& str, size_t* idx = 0, int base = 10);
- 所屬頭文件為string.h
- 參數:
- str:表示所要轉化的字符串
- idx:表示想要str中開始轉化的位置,默認為從第一個字符開始。
- base:表示要用的進制(如2進制、16進制,默認為10進制)轉化為int類型十進制數字。
二、例子
// stoi example
#include <iostream> // std::cout
#include <string> // std::string, std::stoi
int main ()
{
std::string str_dec = "2001, A Space Odyssey";
std::string str_hex = "40c3";
std::string str_bin = "-10010110001";
std::string str_auto = "0x7f";
std::string::size_type sz; // alias of size_t
int i_dec = std::stoi (str_dec,&sz);
int i_hex = std::stoi (str_hex,nullptr,16);
int i_bin = std::stoi (str_bin,nullptr,2);
int i_auto = std::stoi (str_auto,nullptr,0);
std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
std::cout << str_hex << ": " << i_hex << '\n';
std::cout << str_bin << ": " << i_bin << '\n';
std::cout << str_auto << ": " << i_auto << '\n';
return 0;
}
OUT:
2001, A Space Odyssey: 2001 and [, A Space Odyssey]
40c3: 16579
-10010110001: -1201
0x7f: 127