函式模板
<string>

std::stol

long stol (const string&  str, size_t* idx = 0, int base = 10);long stol (const wstring& str, size_t* idx = 0, int base = 10);
將字串轉換為長整數
該函式解析str,將其內容解釋為指定base的整型數字,並將其作為以下型別的值返回:long int.

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

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

引數

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

返回值

成功時,函式將轉換後的整型數字作為以下型別的值返回:long 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
// stol example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stol

int main ()
{
  std::string str_dec = "1987520";
  std::string str_hex = "2f04e009";
  std::string str_bin = "-11101001100100111010";
  std::string str_auto = "0x7fffff";

  std::string::size_type sz;   // alias of size_t

  long li_dec = std::stol (str_dec,&sz);
  long li_hex = std::stol (str_hex,nullptr,16);
  long li_bin = std::stol (str_bin,nullptr,2);
  long li_auto = std::stol (str_auto,nullptr,0);

  std::cout << str_dec << ": " << li_dec << '\n';
  std::cout << str_hex << ": " << li_hex << '\n';
  std::cout << str_bin << ": " << li_bin << '\n';
  std::cout << str_auto << ": " << li_auto << '\n';

  return 0;
}

輸出
1987520: 1987520
2f04e009: 788848649
-11101001100100111010: -956730
0x7fffff: 8388607


複雜度

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

資料競爭

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

異常

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

)。如果讀取的值超出了long int,則會丟擲 invalid_argumentout_of_range 異常。

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

另見