C/C++编程笔记:stoll和strtoll函数,字符串转换

前言

stoll和strtoll函数,都是字符串转换为long long的函数。

std::stoll函数

字符串转换为long long的函数。 对应的还有stoistol,atoi,atol, atoll等。

https://zh.cppreference.com/cpp/string/basic_string/stol

函数

long long stoll( const std::string& str,
                 std::size_t* pos = nullptr, int base = 10 );

参数

str - 要转换的字符串

pos - 存储已处理字符数的整数的地址

base - 数的底

返回值

对应 str 内容的整数值。

异常

无法进行转换时会抛出 std::invalid_argument。 转换值会落在结果类型的范围外,或底层函数(即 std::strtol 或 std::strtoll)将 errno 设置为 ERANGE 时会抛出 std::out_of_range。

std::strtoll函数

字符串指针 转换为long long的函数。 对应的还有strtol等。

https://zh.cppreference.com/cpp/string/byte/strtol

函数

long long strtoll( const char* str, char** str_end, int base );

参数

str - 指向要转译的空终止字符串的指针

str_end - 指向指向字符指针的指针。

base - 被转译整数值的底

返回值

若成功,则返回对应 str 内容的整数值。 若转换出的值落在对应类型的范围外,则发生值域错误(设置 errno 为 ERANGE)并返回 LONG_MAX、LONG_MIN、LLONG_MAX 或 LLONG_MIN(取决于值的符号和返回类型)。 若不能进行转换,则返回 0。

核心区别

特性std::strtollstd::stoll
头文件<cstdlib><string>
函数签名long long strtoll(const char* str, char** endptr, int base)long long stoll(const string& str, size_t* idx = nullptr, int base = 10)
参数类型C 风格字符串 (const char*)C++ std::string(及其子串)
错误处理通过 errnoendptr 检测抛出异常 (std::invalid_argument, std::out_of_range)
C++ 风格C 标准库函数,偏底层C++11 引入,更现代
解析位置控制可通过 endptr 知道解析停止位置可通过 idx 知道解析了多少字符

选择建议

场景推荐
使用 std::string,代码风格偏现代 C++std::stoll
需要与 C 代码交互,或处理 const char*std::strtoll
项目中禁用异常std::strtoll
需要知道解析停止的精确位置两者都可以(endptr / idx
需要自动检测进制(如 0x 前缀)std::strtoll(base=0)或 std::stoll(base=0)
性能敏感、底层解析std::strtoll(开销略低)

总结

  • std::stoll 是更"现代 C++"的选择,接口更友好,但依赖异常机制。

  • std::strtoll 更底层、更灵活,适合异常敏感环境或需要与 C 代码协作的场景。

  • 两者在功能上几乎等价,选择主要取决于你的错误处理策略和字符串类型。

点赞

本文标签: c++

版权声明:本博客所有文章除特别声明外,本文皆为《shiver blog》原创,转载请保留文章出处。

本文链接:C/C++编程笔记:stoll和strtoll函数,字符串转换 - https://www.binary-monster.top/article/98

1

发表评论

电子邮件地址不会被公开。 必填项已用*标注