CJCoding With Joseph
15free / daySign inCreate account

Parse a Quantity with Clear Messages

std::stoi turns text into an int, but it reports problems with two library exceptions: a std::invalid_argument when the text does not start with a number, and a std::out_of_range when the number does not fit in an int. Write parseQuantity(const std::string& text) that returns std::stoi(text) and translates both failures into ONE type with a message of your own: a std::runtime_error saying Not a number: followed by the text, or Number too large: followed by the text. Throwing a new exception from inside a catch is allowed; it replaces the library one. The library messages from what() differ between compilers, which is why the function never passes them on.

The tests read one line of input at a time and print quantity: and the value, or error: and your message. For the input lines 12, abc and 7 the output is shown in Expected Output.

Do NOT write a main function.

Expected Output:

quantity: 12
error: Not a number: abc
quantity: 7

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Exceptions
📥 Auto-Input:
12\nabc\n7\n
This input is automatically fed to your program's stdin
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.