std::optional

Lab C++ Intermediate 20 points

Write optional<int> parsePositive(const string&) that returns a value only for strings of digits (no sign) that fit in an int. Print each parsed value doubled or invalid.

Input

n, then n words.

Output

n lines.

Example

Input

4
21
abc
-5
007

Output

42
invalid
invalid
14
Sample input available Sample output available
Editor
C++

Hints

Return nullopt for "no value".

if (auto v = f()) tests and unpacks in one line.

Solution explanation

Without exceptions, optional is the clean way to report "no result".

Show solution
#include <iostream>
#include <optional>
#include <string>
using namespace std;

optional<int> parsePositive(const string &s) {
    if (s.empty() || s.size() > 9) return nullopt;
    int value = 0;
    for (char c : s) {
        if (c < '0' || c > '9') return nullopt;
        value = value * 10 + (c - '0');
    }
    return value;
}

int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        string s;
        cin >> s;
        if (auto v = parsePositive(s)) cout << *v * 2 << "\n";
        else cout << "invalid\n";
    }
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD