Challenge: Safe Number Reader

Lab C++ Intermediate 20 points

Read n and then n words. Each word should be a whole number, but some aren't. Write a function bool toNumber(const string& s, int& out) that returns false if s is not a valid number (digits only, with an optional leading -). Print the sum of the valid numbers and how many words were skipped.

Input

n, then n words.

Output

Sum: 12
Skipped: 2

Example

Input

5
4 abc 8 1x2 0

Output

Sum: 12
Skipped: 2
Sample input available Sample output available
Editor
C++

Hints

Check every character with isdigit; allow a '-' only as the first character.

A lone "-" is not a number.

Only call stoi after you've checked the word is valid.

Solution explanation

Checking the input first means stoi is never given bad text, so no exception can happen.

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

bool toNumber(const string& s, int& out) {
    int start = 0;
    if (!s.empty() && s[0] == '-') {
        start = 1;
    }
    if (start == static_cast<int>(s.length())) {
        return false;
    }
    for (int i = start; i < static_cast<int>(s.length()); i++) {
        if (!isdigit(s[i])) {
            return false;
        }
    }
    out = stoi(s);
    return true;
}

int main() {
    int n;
    cin >> n;
    int sum = 0, skipped = 0;
    for (int i = 0; i < n; i++) {
        string word;
        cin >> word;
        int value;
        if (toNumber(word, value)) {
            sum += value;
        } else {
            skipped++;
        }
    }
    cout << "Sum: " << sum << "\n";
    cout << "Skipped: " << skipped << "\n";
    return 0;
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD