Namespaces
Variants

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

From cppreference.net
定义于头文件 <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; // 使用负数计算以支持 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库对 atoi atoil atoll 的实现方式,这些实现要么直接实现该功能(如 MUSL libc ),要么委托给 strtol / strtoll 处理(如 GNU libc )。

示例

#include <cstdlib>
#include <iostream>
int main()
{
    const auto data =
    {
        "42",
        "0x2A", // 被解析为 "0" 和无效字符 "x2A",而非十六进制
        "3.14159",
        "31337 with words",
        "words and 2",
        "-012345",
        "10000000000" // 注意:超出 int32_t 范围
    };
    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)
将字符串转换为有符号整数
(函数)
(C++11) (C++11)
将字符串转换为无符号整数
(函数)
将字节字符串转换为整数值
(函数)
将字节字符串转换为无符号整数值
(函数)
(C++11) (C++11)
将字节字符串转换为 std::intmax_t std::uintmax_t
(函数)
(C++17)
将字符序列转换为整数或浮点数值
(函数)
C 文档 用于 atoi , atol , atoll