简体   繁体   中英

std::stoi, std::setbase, and an std::out_of_range error

Using std::setbase to format a number to pass the numeric minimum of int to std::stoi throws an std::out_of_range exception, but I do not understand why. If anyone can help me to better understand the reasoning behind the exception, I would greatly appreciate it.

Code Snippet:

#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; 
}   

Output:

base-10: -2147483648 
base-16: 80000000 
terminate called after throwing an instance of 'std::out_of_range'
  what():  stoi 
Aborted (core dumped)

The std::stoX functions will not return a negative value for a string that is not prefixed with - . 0x80000000 is 2 31 , which is not representable by a signed 32-bit integer, so there is overflow and consequently an exception is raised.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM