std::atoi, std::atol, std::atoll
来自cppreference.com
在标头 <cstdlib> 定义 | ||
int atoi(constchar* str ); | (1) | |
long atol(constchar* str ); | (2) | |
longlong atoll(constchar* str ); | (3) | (C++11 起) |
转译 str 所指向的字节字符串中的整数值。蕴含的基数总是 10。
舍弃任何空白符,直至找到首个非空白符,然后接收尽可能多的字符以组成合法的整数表示,并转换之为整数。合法的整数含下列部分:
- (可选) 正或负号
- 数位
如果结果的值无法被表示,即转换后的值落在对应返回类型之外,则其行为未定义。
目录 |
[编辑]参数
str | - | 指向要转译的空终止字节字符串的指针 |
[编辑]返回值
成功时为对应 str 内容的整数值。
若不能进行转换,则返回 0。
[编辑]可能的实现
template<typename T> T atoi_impl(constchar* str){while(std::isspace(static_cast<unsignedchar>(*str)))++str; bool negative =false; if(*str =='+')++str;elseif(*str =='-'){++str; negative =true;} T result =0;for(;std::isdigit(static_cast<unsignedchar>(*str));++str){int digit =*str -'0'; result *=10; result -= digit;// 计算负值,以支持 INT_MIN, LONG_MIN,..} return negative ? result :-result;} int atoi(constchar* str){return atoi_impl<int>(str);} long atol(constchar* str){return atoi_impl<long>(str);} longlong atoll(constchar* str){return atoi_impl<longlong>(str);} |
实际的 C++ 库实现会回退到 atoi
、atoil
和 atoll
的 C 库实现,而后者则直接实现(如 MUSL libc 中)或者委托给 strtol/strtoll(如 GNU libc)。
[编辑]示例
运行此代码
#include <cstdlib>#include <iostream> int main(){constauto data ={"42", "0x2A", // 被当做 "0" 后面跟着 "x2A",而非十六进制"3.14159", "31337 with words", "words and 2", "-012345", "10000000000"// 注:在 int32_t 的范围之外}; for(constchar* s : data){constint i{std::atoi(s)};std::cout<<"std::atoi('"<< s <<"') is "<< i <<'\n';if(constlonglong 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) | 转换字节字符串为无符号整数值 (函数) |
(C++11)(C++11) | 转换字节字符串为 std::intmax_t 或 std::uintmax_t (函数) |
(C++17) | 转换字符序列到整数或浮点数 (函数) |
atoi, atol, atoll 的 C 文档 |