LearnFrenzy
Sign in Take a free test

Exception Handling · Predict the Output · Question 9

Exceptions thrown by std::stoi Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <stdexcept>
#include <string>

int main() {
    int sum = 0;
    for (std::string s : {"12", "7abc", "x9", "99999999999", " 4"}) {
        try { sum += std::stoi(s); }
        catch (const std::invalid_argument&) { std::cout << "invalid "; }
        catch (const std::out_of_range&) { std::cout << "range "; }
    }
    std::cout << sum << '\n';
    return 0;
}
  • A invalid range 23 Correct
  • B invalid invalid range invalid 12
  • C invalid range 19
  • D invalid invalid range 16
Correct Answer: Option A

stoi reads leading digits ("7abc" gives 7) and skips leading spaces (" 4" gives 4). Only "x9" has no number, and 99999999999 does not fit an int: 12 + 7 + 4 = 23.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links