YASH NEMA
YASH NEMA

Reputation: 11

terminate called after throwing an instance of 'std::out_of_range' what(): stoi

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

Upvotes: 0

Views: 3131

Answers (2)

anastaciu
anastaciu

Reputation: 23822

When you reverse 1534236469 you get 9646324351, that does not fit an int, the maximum value for an int, in most cases, is 2147483647.

Use stoll instead of stoi and use long long instead of int for x variable type, otherwise the assignment will overflow and cause undefined behavior.

Upvotes: 6

Derek T. Jones
Derek T. Jones

Reputation: 1822

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.

Upvotes: 1

Related Questions