← Back to Question List
C++ Code Walkthrough #122
A Function That Reports Instead of Crashing
📄 Code
Read carefully — what does this print?1#include <iostream>2#include <stdexcept>3#include <string>45int parsePercent(const std::string& text) {6 int value = std::stoi(text);7 if (value < 0 || value > 100) {8 throw std::out_of_range("percent must be 0 to 100");9 }10 return value;11}1213std::string report(const std::string& text) {14 try {15 int value = parsePercent(text);16 return "ok " + std::to_string(value);17 } catch (const std::out_of_range& e) {18 return std::string("range: ") + e.what();19 } catch (const std::invalid_argument&) {20 return "not a number";21 }22}2324int main() {25 std::string inputs[] = {"50", "150", "abc", "0"};26 for (const std::string& text : inputs) {27 std::cout << report(text) << "\n";28 }29 return 0;30}