Namespaces
Variants

std:: strtol, std:: strtoll

From cppreference.net
定义于头文件 <cstdlib>
long strtol ( const char * str, char ** str_end, int base ) ;
(1)
long long strtoll ( const char * str, char ** str_end, int base ) ;
(2) (C++11 起)

str 所指向的字节字符串中的整数值进行解析。

丢弃所有空白字符(通过调用 std::isspace 识别),直到找到第一个非空白字符,然后尽可能提取字符以构成有效的 base-n (其中n= base )整数表示形式,并将其转换为整数值。有效的整数值由以下部分组成:

  • (可选) 正负号
  • (可选) 前缀 ( 0 ) 表示八进制基数(仅当基数为 8 0 时适用)
  • (可选) 前缀 ( 0x 0X ) 表示十六进制基数(仅当基数为 16 0 时适用)
  • 数字序列

基数的有效取值范围为 {0, 2, 3, ..., 36} 。对于基数为 2 的整数,有效数字集为 {0, 1} ;对于基数为 3 的整数,有效数字集为 {0, 1, 2} ,依此类推。对于大于 10 的基数,有效数字包含字母字符:从基数为 11 的整数使用 Aa 开始,到基数为 36 的整数使用 Zz 结束。字符的大小写将被忽略。

当前安装的 C locale 可能接受其他数字格式。

如果 base 的值为 0 ,将自动检测数值进制:若前缀为 0 则为八进制,若前缀为 0x 0X 则为十六进制,否则为十进制。

如果减号是输入序列的一部分,则根据数字序列计算出的数值将被取反,如同通过结果类型的 一元减号运算符 进行处理。

该函数将 str_end 所指向的指针设置为指向最后一个被解释字符之后的位置。如果 str_end 是空指针,则此参数将被忽略。

如果 str 为空或不具有预期格式,则不执行转换,并且(若 str_end 不是空指针)将 str 的值存入 str_end 所指向的对象中。

目录

参数

str - 指向待解析的空终止字节字符串的指针
str_end - 指向字符指针的指针
base - 被解析整数值的 基数

返回值

示例

#include <cerrno>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <string>
int main()
{
    const char* p = "10 200000000000000000000000000000 30 -40";
    std::cout << "正在解析 " << std::quoted(p) << ":\n";
    for (;;)
    {
        // errno 可能被库函数调用设置为任意非零值
        // 无论是否发生错误,因此需要先清除
        // 才能检查 strtol 设置的错误
        errno = 0;
        char* p_end{};
        const long i = std::strtol(p, &p_end, 10);
        if (p == p_end)
            break;
        const bool range_error = errno == ERANGE;
        const std::string extracted(p, p_end - p);
        p = p_end;
        std::cout << "已提取 " << std::quoted(extracted)
                  << ", strtol 返回 " << i << '.';
        if (range_error)
            std::cout << "\n  发生范围错误。";
        std::cout << '\n';
    }
}

可能的输出:

正在解析 "10 200000000000000000000000000000 30 -40":
已提取 "10", strtol 返回 10。
已提取 " 200000000000000000000000000000", strtol 返回 9223372036854775807。
  发生范围错误。
已提取 " 30", strtol 返回 30。
已提取 " -40", strtol 返回 -40。

参见

(C++11) (C++11) (C++11)
将字符串转换为有符号整数
(函数)
将字节字符串转换为无符号整数值
(函数)
(C++11) (C++11)
将字节字符串转换为 std::intmax_t std::uintmax_t
(函数)
将宽字符串转换为整数值
(函数)
将字节字符串转换为浮点数值
(函数)
(C++17)
将字符序列转换为整数或浮点数值
(函数)
将字节字符串转换为整数值
(函数)
C 文档 用于 strtol , strtoll