C++: Safe conversion

Convert text to a number without crashing.

What to build

A program that handles one expected error.

Requirements

  • Read each word until the input ends.
  • If it converts with stoi, print double its value.
  • Otherwise, print bad.

Input

Words separated by spaces.

Output

One line per word.

Constraints

There are from 1 to 50 words, each of up to 8 characters. Numbers have no other characters after them.

Example

Input:

21 abc

Output:

42
bad

Why it works

stoi signals bad text by throwing, so the normal path stays uncluttered, and only the failing word is affected.

Examples

Example 1 · Input
21 abc
Expected output
42
bad
Example 2 · Input
0
Expected output
0

Hints

Hint 1

Put the stoi call inside try.

Hint 2

stoi throws invalid_argument for text that is not a number.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

int main() {
    string word;
    while (cin >> word) {
        try {
            cout << stoi(word) * 2 << endl;
        } catch (const invalid_argument& e) {
            cout << "bad" << endl;
        }
    }
    return 0;
}

Lesson: Exceptions and files →