加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – std :: stoi,std :: setbase和std :: out_of_range错误

发布时间:2020-12-16 09:56:22 所属栏目:百科 来源:网络整理
导读:使用std :: setbase格式化数字以将int的数字最小值传递给std :: stoi会抛出std :: out_of_range异常,但我不明白为什么.如果有人能帮助我更好地理解异常背后的推理,我将非常感激. 代码片段: #include iomanip#include iostream#include limits#include sstre
使用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位整数表示,因此存在溢出,因此引发异常.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读