gpt4 book ai didi

c++ - std::stoi、std::setbase 和 std::out_of_range 错误

转载 作者:太空狗 更新时间:2023-10-29 20:12:19 34 4
gpt4 key购买 nike

使用 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com