CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List
C++ Code Walkthrough #114

Two Ways stoi Can Fail

mediumExceptions

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <stdexcept>
3#include <string>
4 
5int main() {
6 std::string inputs[] = {"12", "abc", "99999999999999999999", "-4"};
7 for (const std::string& text : inputs) {
8 try {
9 int number = std::stoi(text);
10 std::cout << "parsed " << number << "\n";
11 } catch (const std::invalid_argument&) {
12 std::cout << "not a number: " << text << "\n";
13 } catch (const std::out_of_range&) {
14 std::cout << "too big for an int: " << text << "\n";
15 }
16 }
17 return 0;
18}

🎯 Your Answer