Reputation: 837
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)
Upvotes: 3
Views: 1427
Reputation: 62995
The std::stoX
functions will not return a negative value for a string that is not prefixed with -
. 0x80000000
is 231, which is not representable by a signed 32-bit integer, so there is overflow and consequently an exception is raised.
Upvotes: 7