std::stoi, std::setbase, and an std::out_of_range error
std::stoi, std::setbase, and an std::out_of_range error
使用std::setbase格式化一个数字,将数值最小值int传递给std::stoi会抛出std::out_of_range异常,但我不明白为什么。如果有人能帮助我更好地理解异常背后的原因,我将不胜感激
代码段:
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
template <typename T>
std::string toString(const T x, const int base)
{
std::stringstream ss;
ss << std::setbase(base) << x;
return ss.str();
}
int main(void)
{
const int x = std::numeric_limits<int>::min();
std::size_t index = 0;
const auto base = 16;
const auto s = toString(x, base);
std::cout << "base-10: " << x << std::endl
<< "base-" << base << ": " << s << std::endl;
std::cout << std::stoi(s, &index, base) << std::endl;
return 0;
}
输出:
base-10: -2147483648
base-16: 80000000
terminate called after throwing an instance of 'std::out_of_range'
what(): stoi
Aborted (core dumped)
std::stoX
函数不会为没有前缀为-
的字符串返回负值。0x80000000
是231,它不能用有符号的32位整数表示,因此存在溢出,因此引发异常。
相关文章:
- Usages of std::move
- 具有变量Number of Arguments的std::函数的矢量
- constexpr begin of a std::array
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- Centos7 g++ "to_string is not in a member of std"
- 传递 std::vector of std::shared_ptr,而不是更新对象
- 初始化 std::数组 of Eigen::Map
- 从返回 std::optional of std::vector 的函数中获取结果到调用方
- PyBind11:返回对 std::vector of std::unique_ptr 的常量引用
- 是否可以使用 std::variant of std::variants
- What is the std::chrono::time_point equivalent of std::numer
- python equivalent of std::chrono::steady_clock::now();
- Strange behavior of std::vector<{QString,int*}>
- 如何在 std::map 中从 std::vector of std::p air 中获取输入?
- 使用 operator[] 访问私有 std::map of unique_ptr
- "terminate called after throwing an instance of std::invalid_argument' what(): stoi ?"
- 在 std::unordered_map 中插入新的键/值对会导致"out of range"异常
- 使类在流上模板化处理std::cout和std::of流
- 使用初始化器列表初始化类中的std::of流
- std::of流默认情况下是截断还是附加