函式模板
<string>

std::stoi

int stoi (const string&  str, size_t* idx = 0, int base = 10);int stoi (const wstring& str, size_t* idx = 0, int base = 10);
將字串轉換為整數
解析str,將其內容解釋為指定base的整型數字,然後返回一個intlong int

的值返回。如果idx不是空指標,函式還會將idx的值設定為str中數字之後第一個字元的位置。

該函式使用 strtol (或 wcstol)進行轉換(有關轉換過程的更多詳細資訊,請參閱 strtol)。

引數

str
具有整型數字表示的字串物件。
idx
指向型別為 size_t 的物件的指標,其值由函式設定為str中數值之後下一個字元的位置。
該引數也可以是一個空指標,此時它將不被使用。
base
決定有效字元及其解釋的數字基數(radix)。
如果這個0,則使用的基數由序列中的格式確定(有關詳細資訊,請參閱strtol)。請注意,預設情況下此引數為10,而不是0.

返回值

成功時,該函式將其轉換後的整型數字作為intlong int

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 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;
}

輸出

2001, A Space Odyssey: 2001 and [, A Space Odyssey]
40c3:  16579
-10010110001: -1201
0x7f: 127


複雜度

未定義,但通常與解釋的字元數呈線性關係。

資料競爭

修改idx指向的值 (如果idx不為零)。

異常

如果無法執行任何轉換,則丟擲invalid_argument異常。

如果讀取的值超出了可表示範圍int,則丟擲out_of_range異常。

無效的idx會導致未定義行為

另見