名稱空間
變體
操作

std::strtoul, std::strtoull

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

解釋由 str 指向的位元組字串中的無符號整型值。

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

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

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

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

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

如果減號是輸入序列的一部分,則從數字序列計算出的數值會被取反,就像結果型別中的一元減號一樣,這會應用無符號整數的環繞規則。

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

目錄

[編輯] 引數

str - 指向要解釋的空終止位元組字串的指標
str_end - 指向字元指標的指標,可能被設定為指向最後一個被解釋字元之後的位置
base - 被解釋整數值的*基數*

[編輯] 返回值

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

[編輯] 示例

#include <cstdlib>
#include <errno.h>
#include <iostream>
#include <string>
 
int main()
{
    const char* p = "10 200000000000000000000000000000 30 -40 - 42";
    char* end = nullptr;
    std::cout << "Parsing '" << p << "':\n";
    for (unsigned long i = std::strtoul(p, &end, 10);
        p != end;
        i = std::strtoul(p, &end, 10))
    {
        std::cout << "'" << std::string(p, end - p) << "' -> ";
        p = end;
        if (errno == ERANGE)
        {
            errno = 0;
            std::cout << "range error, got ";
        }
        std::cout << i << '\n';
    }
    std::cout << "After the loop p points to '" << p << "'\n";
}

可能的輸出

Parsing '10 200000000000000000000000000000 30 -40 - 42':
'10' -> 10
' 200000000000000000000000000000' -> range error, got 18446744073709551615
' 30' -> 30
' -40' -> 18446744073709551576
After the loop p points to ' - 42'

[編輯] 參閱

(C++11)(C++11)
將字串轉換為無符號整數
(函式) [編輯]
將位元組字串轉換為整數值
(函式) [編輯]
(C++11)(C++11)
將位元組字串轉換為 std::intmax_tstd::uintmax_t
(函式) [編輯]
將寬字串轉換為無符號整數值
(函式) [編輯]
將位元組字串轉換為浮點值
(函式) [編輯]
將字元序列轉換為整數或浮點值
(函式) [編輯]
將位元組字串轉換為整數值
(函式) [編輯]
C 文件 用於 strtoul, strtoull