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

c – std :: stoi,std :: setbase和std :: out_of_range错误,第1张

概述使用std :: setbase格式化数字以将int的数字最小值传递给std :: stoi会抛出std :: out_of_range异常,但我不明白为什么.如果有人能帮助我更好地理解异常背后的推理,我将非常感激. 代码片段: #include <iomanip>#include <iostream>#include <limits>#include <sstream>template 使用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错误全部内容,希望文章能够帮你解决c – std :: stoi,std :: setbase和std :: out_of_range错误所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1216485.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存