Challenge: Safe Number Reader
Completed
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
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
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module