strtoimax, strtoumax
來自 cppreference.com
在標頭檔案 <inttypes.h> 中定義 |
||
intmax_t strtoimax( const char* restrict nptr, char** restrict endptr, int base ); |
(1) | (C99 起) |
uintmax_t strtoumax( const char* restrict nptr, char** restrict endptr, int base ); |
(2) | (C99 起) |
將 nptr 指向的位元組字串解釋為整數值。
丟棄任何空白字元(透過呼叫 isspace 識別),直到找到第一個非空白字元,然後儘可能多地獲取字元以形成有效的 base-n(其中 n=base
)整數表示,並將其轉換為整數值。有效的整數值包含以下部分:
- (可選) 加號或減號
- (可選) 字首 (
0
) 表示八進位制基數(僅當基數為 8 或 0 時適用) - (可選) 字首 (
0x
或0X
) 表示十六進位制基數(僅當基數為 16 或 0 時適用) - 一系列數字
base
的有效值集為 {0, 2, 3, ..., 36}
。基數為 2
的整數的有效數字集為 {0, 1}
,基數為 3
的整數為 {0, 1, 2}
,依此類推。對於大於 10
的基數,有效數字包括字母字元,從基數 11
的整數的 Aa
開始,到基數 36
的整數的 Zz
結束。字元的大小寫被忽略。
當前安裝的 C 區域設定可能會接受其他數字格式。
如果 base
的值為 0,則自動檢測數字基數:如果字首是 0
,則基數為八進位制;如果字首是 0x
或 0X
,則基數為十六進位制;否則基數為十進位制。
如果負號是輸入序列的一部分,則從數字序列計算出的數值將被取反,如同結果型別中的一元減號一樣。
函式將 endptr 指向的指標設定為指向最後一個被解釋字元之後的字元。如果 endptr 是空指標,則忽略它。
如果 nptr 為空或不具有預期格式,則不執行轉換,並且(如果 endptr 不是空指標)nptr 的值儲存在 endptr 所指向的物件中。
目錄 |
[編輯] 引數
nptr | - | 指向要解釋的空終止位元組字串的指標 |
endptr | - | 指向字元指標的指標 |
base | - | 被解釋整數值的*基數* |
[編輯] 返回值
- 如果成功,返回與
str
內容對應的整數值。 - 如果轉換後的值超出相應返回型別的範圍,則會發生範圍錯誤(將 errno 設定為 ERANGE),並根據情況返回 INTMAX_MAX、INTMAX_MIN、UINTMAX_MAX 或 0。
- 如果無法執行轉換,則返回 0。
[編輯] 示例
執行此程式碼
#include <errno.h> #include <inttypes.h> #include <stdio.h> #include <string.h> int main(void) { char* endptr = NULL; printf("%ld\n", strtoimax(" -123junk", &endptr, 10)); // base 10 printf("%ld\n", strtoimax("11111111", &endptr, 2)); // base 2 printf("%ld\n", strtoimax("XyZ", &endptr, 36)); // base 36 printf("%ld\n", strtoimax("010", &endptr, 0)); // octal auto-detection printf("%ld\n", strtoimax("10", &endptr, 0)); // decimal auto-detection printf("%ld\n", strtoimax("0x10", &endptr, 0)); // hexadecimal auto-detection // range error: LONG_MAX+1 --> LONG_MAX errno = 0; printf("%ld\n", strtoimax("9223372036854775808", &endptr, 10)); printf("%s\n", strerror(errno)); }
輸出
-123 255 44027 8 10 16 9223372036854775807 Numerical result out of range
[編輯] 參考
- C23 標準 (ISO/IEC 9899:2024)
- 7.8.2.3 strtoimax 和 strtoumax 函式 (p: TBD)
- C17 標準 (ISO/IEC 9899:2018)
- 7.8.2.3 strtoimax 和 strtoumax 函式 (p: TBD)
- C11 標準 (ISO/IEC 9899:2011)
- 7.8.2.3 strtoimax 和 strtoumax 函式 (p: 219)
- C99 標準 (ISO/IEC 9899:1999)
- 7.8.2.3 strtoimax 和 strtoumax 函式 (p: 200)
[編輯] 另請參閱
(C99)(C99) |
將寬字串轉換為 intmax_t 或 uintmax_t (函式) |
(C99) |
將位元組字串轉換為整數值 (函式) |
(C99) |
將位元組字串轉換為無符號整數值 (函式) |