- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
使用 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 位整数表示,因此存在溢出并因此引发异常。
关于c++ - std::stoi、std::setbase 和 std::out_of_range 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28419636/
我正在处理一个比较大的项目,我发现有人添加了一些与此类似的代码: std::cout push %ebp x0x84ca2e9 mov
我发现如果我在 setBase(SystemClock.elapsedRealtime()) 之后立即调用 start() 它将从 00:00 开始计数(这很好),见下文: startButton.s
拓扑助手 Ipv4AddressHelper 允许设置基地址,如示例所示。 Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.2
The cppreference page on std::setbase说: Values of base other than 8, 10, or 16 reset basefield to ze
本文整理了Java中com.google.gdata.util.XmlBlob.setBase()方法的一些代码示例,展示了XmlBlob.setBase()的具体用法。这些代码示例主要来源于Gith
long int id; printf("Enter Aircraft Id: (eg abeb11"); scanf("%x",&id); id" 必须读取为十六进制值。但我收到警告 format
std::cout<
使用 std::setbase 格式化数字以将 int 的数字最小值传递给 std::stoi 会引发 std::out_of_range 异常,但我不明白为什么。如果有人能帮助我更好地理解异常背后的
我是一名优秀的程序员,十分优秀!