std::atoi, std::atol, std::atoll
来自cppreference.com
<tbody>
</tbody>
| 在标头 <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++ 库实现会回退到 atoi、atoil 和 atoll 的 C 库实现,而后者则直接实现(如 MUSL libc 中)或者委托给 std::strtol/std::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) |
转换字节字符串为无符号整数值 (函数) |
(C++11)(C++11) |
转换字节字符串为 std::intmax_t 或 std::uintmax_t (函数) |
(C++17) |
转换字符序列到整数或浮点数 (函数) |
atoi, atol, atoll 的 C 文档
| |