Why I am getting this error on input 1534236469
in the below code?
terminate called after throwing an instance of 'std::out_of_range' what(): stoi
int reverse(int x) {
string s = to_string(x);
for (int i = 0; i < s.size() / 2; i ) {
swap(s[i], s[s.size() - 1 - i]);
}
if (x < 0) {
x = -stoi(s);
} else {
x = stoi(s);
}
return x;
}
CodePudding user response:
When you reverse 1534236469
you get 9646324351
, that does not fit an int
, the max value for an int
in most cases is 2147483647
.
Use stoll
instead and use long long
instead of int
for x
, otherwise the assignment will overflow and cause undefined behavior.
CodePudding user response:
You've got two questions: why is terminate()
being called, and why is out_of_range()
being thrown?
terminate()
is being called, per the standard, because you don't have an exception handler (you didn't surround your call to reverse
with try...catch
).
out_of_range()
is being thrown by stoi
because the value it's given is out of range for an int
. 9646324351
, as @anastaciu points out, is outside the range of an int
on your machine.