名稱空間
變體
操作

std::atoi, std::atol, std::atoll

來自 cppreference.com
< cpp‎ | string‎ | byte
定義於標頭檔案 <cstdlib>
int       atoi( const char* str );
(1)
long      atol( const char* str );
(2)
long long atoll( const char* str );
(3) (C++11 起)

str 指向的位元組字串解釋為整數值。隱含的基數始終是 10。

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

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

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

目錄

[編輯] 引數

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

[編輯] 返回值

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

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

[編輯] 可能的實現

template<typename T>
T atoi_impl(const char* str)
{
    while (std::isspace(static_cast<unsigned char>(*str)))
        ++str;
 
    bool negative = false;
 
    if (*str == '+')
        ++str;
    else if (*str == '-')
    {
        ++str;
        negative = true;
    }
 
    T result = 0;
    for (; std::isdigit(static_cast<unsigned char>(*str)); ++str)
    {
        int digit = *str - '0';
        result *= 10;
        result -= digit; // calculate in negatives to support INT_MIN, LONG_MIN,..
    }
 
    return negative ? result : -result;
}
 
int atoi(const char* str)
{
    return atoi_impl<int>(str);
}
 
long atol(const char* str)
{
    return atoi_impl<long>(str);
}
 
long long atoll(const char* str)
{
    return atoi_impl<long long>(str);
}

實際的 C++ 庫實現會回退到 C 庫中 atoiatoilatoll 的實現,這些實現要麼直接實現(如 MUSL libc),要麼委託給 strtol/strtoll(如 GNU libc)。

[編輯] 示例

#include <cstdlib>
#include <iostream>
 
int main()
{
    const auto data =
    {
        "42",
        "0x2A", // treated as "0" and junk "x2A", not as hexadecimal
        "3.14159",
        "31337 with words",
        "words and 2",
        "-012345",
        "10000000000" // note: out of int32_t range
    };
 
    for (const char* s : data)
    {
        const int i{std::atoi(s)};
        std::cout << "std::atoi('" << s << "') is " << i << '\n';
        if (const long long ll{std::atoll(s)}; i != ll)
            std::cout << "std::atoll('" << s << "') is " << ll << '\n';
    }
}

可能的輸出

std::atoi('42') is 42
std::atoi('0x2A') is 0
std::atoi('3.14159') is 3
std::atoi('31337 with words') is 31337
std::atoi('words and 2') is 0
std::atoi('-012345') is -12345
std::atoi('10000000000') is 1410065408
std::atoll('10000000000') is 10000000000

[編輯] 參閱

(C++11)(C++11)(C++11)
將字串轉換為有符號整數
(function) [編輯]
(C++11)(C++11)
將字串轉換為無符號整數
(function) [編輯]
將位元組字串轉換為整數值
(function) [編輯]
將位元組字串轉換為無符號整數值
(function) [編輯]
(C++11)(C++11)
將位元組字串轉換為 std::intmax_tstd::uintmax_t
(function) [編輯]
將字元序列轉換為整數或浮點值
(function) [編輯]
C 文件 用於 atoi, atol, atoll