名稱空間
變體
操作

std::strtol, std::strtoll

來自 cppreference.com
< cpp‎ | string‎ | byte
定義於標頭檔案 <cstdlib>
long      strtol( const char* str, char** str_end, int base );
(1)
long long strtoll( const char* str, char** str_end, int base );
(2) (C++11 起)

解釋由 str 指向的位元組字串中的整數值。

丟棄所有空白字元(透過呼叫 std::isspace 識別),直到找到第一個非空白字元,然後儘可能多地獲取字元以形成有效的 *基數-n*(其中 n=base)整數表示,並將其轉換為整數值。有效的整數值包含以下部分

  • (可選) 加號或減號
  • (可選) 字首 (0) 表示八進位制基數(僅當基數為 80 時適用)
  • (可選) 字首 (0x0X) 表示十六進位制基數(僅當基數為 160 時適用)
  • 一系列數字

基數的有效值集合是 {0, 2, 3, ..., 36}。基數-2 整數的有效數字集合是 {0, 1},基數-3 整數的有效數字是 {0, 1, 2},依此類推。對於大於 10 的基數,有效數字包括字母字元,從基數-11 整數的 Aa 到基數-36 整數的 Zz。字元的大小寫被忽略。

當前安裝的 C locale 可能會接受其他數字格式。

如果 base 的值為 0,則自動檢測數字基數:如果字首是 0,則基數為八進位制;如果字首是 0x0X,則基數為十六進位制;否則基數為十進位制。

如果減號是輸入序列的一部分,則從數字序列計算出的數值將被取反,如同結果型別中的一元減號

該函式將 str_end 指向的指標設定為指向最後一個被解釋字元之後的字元。如果 str_end 是空指標,則忽略它。

如果 str 為空或不符合預期形式,則不執行轉換,並且(如果 str_end 不是空指標)str 的值儲存在 str_end 指向的物件中。

目錄

[編輯] 引數

str - 指向要解釋的空終止位元組字串的指標
str_end - 指向字元指標的指標
base - 被解釋整數值的*基數*

[編輯] 返回值

  • 如果成功,則返回與 str 內容對應的整數值。
  • 如果轉換後的值超出相應返回型別的範圍,則發生範圍錯誤(將 errno 設定為 ERANGE),並返回 LONG_MAXLONG_MINLLONG_MAXLLONG_MIN
  • 如果無法執行轉換,則返回 0

[編輯] 示例

#include <cerrno>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <string>
 
int main()
{
    const char* p = "10 200000000000000000000000000000 30 -40";
    std::cout << "Parsing " << std::quoted(p) << ":\n";
 
    for (;;)
    {
        // errno can be set to any non-zero value by a library function call
        // regardless of whether there was an error, so it needs to be cleared
        // in order to check the error set by strtol
        errno = 0;
        char* p_end{};
        const long i = std::strtol(p, &p_end, 10);
        if (p == p_end)
            break;
 
        const bool range_error = errno == ERANGE;
        const std::string extracted(p, p_end - p);
        p = p_end;
 
        std::cout << "Extracted " << std::quoted(extracted)
                  << ", strtol returned " << i << '.';
        if (range_error)
            std::cout << "\n  Range error occurred.";
 
        std::cout << '\n';
    }
}

可能的輸出

Parsing "10 200000000000000000000000000000 30 -40":
Extracted "10", strtol returned 10.
Extracted " 200000000000000000000000000000", strtol returned 9223372036854775807.
  Range error occurred.
Extracted " 30", strtol returned 30.
Extracted " -40", strtol returned -40.

[編輯] 另請參閱

(C++11)(C++11)(C++11)
將字串轉換為有符號整數
(函式) [編輯]
將位元組字串轉換為無符號整數值
(函式) [編輯]
(C++11)(C++11)
將位元組字串轉換為 std::intmax_tstd::uintmax_t
(函式) [編輯]
將寬字串轉換為整數值
(函式) [編輯]
將位元組字串轉換為浮點值
(函式) [編輯]
將字元序列轉換為整數或浮點值
(函式) [編輯]
將位元組字串轉換為整數值
(函式) [編輯]
C documentation for strtol, strtoll