名稱空間
變體
操作

atoi, atol, atoll

來自 cppreference.com
< c‎ | string‎ | byte
在標頭檔案 <stdlib.h> 中定義
int       atoi ( const char* str );
(1)
long      atol ( const char* str );
(2)
long long atoll( const char* str );
(3) (C99 起)

解釋由 str 指向的位元組字串中的整數值。隱含的基數總是 10

丟棄所有空白字元,直到找到第一個非空白字元,然後儘可能多地獲取字元以形成有效的整數數字表示,並將其轉換為整數值。有效的整數值包含以下部分

  • (可選) 加號或減號
  • 數字

如果結果的值不能表示,即轉換後的值超出相應返回型別的範圍,則行為未定義。

目錄

[編輯] 引數

str - 指向要解釋的空終止位元組字串的指標

[編輯] 返回值

成功時,返回對應於 str 內容的整數值。

如果無法執行轉換,則返回 0

[編輯] 注意

名稱代表“ASCII to integer”(ASCII 到整數)。

[編輯] 示例

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    printf("%i\n", atoi(" -123junk"));
    printf("%i\n", atoi(" +321dust"));
    printf("%i\n", atoi("0"));
    printf("%i\n", atoi("0042")); // treated as a decimal number with leading zeros
    printf("%i\n", atoi("0x2A")); // only leading zero is converted discarding "x2A"
    printf("%i\n", atoi("junk")); // no conversion can be performed
    printf("%i\n", atoi("2147483648")); // UB: out of range of int
}

可能的輸出

-123
321
0
42
0
0
-2147483648

[編輯] 參考

  • C23 標準 (ISO/IEC 9899:2024)
  • 7.22.1.2 The atoi, atol, and atoll functions (p: TBD)
  • C17 標準 (ISO/IEC 9899:2018)
  • 7.22.1.2 The atoi, atol, and atoll functions (p: 249)
  • C11 標準 (ISO/IEC 9899:2011)
  • 7.22.1.2 The atoi, atol, and atoll functions (p: 341)
  • C99 標準 (ISO/IEC 9899:1999)
  • 7.20.1.2 The atoi, atol, and atoll functions (p: 307)
  • C89/C90 標準 (ISO/IEC 9899:1990)
  • 4.10.1.2 The atoi function
  • 4.10.1.3 The atol function

[編輯] 另請參閱

將位元組字串轉換為整數值
(函式) [編輯]
將位元組字串轉換為無符號整數值
(函式) [編輯]
(C95)(C99)
將寬字串轉換為整數值
(函式) [編輯]
將寬字串轉換為無符號整數值
(函式) [編輯]
C++ documentation for atoi, atol, atoll