Read lines of "name age" from input; throw a ValidationError for an empty name, a non-numeric age or an age outside 1–120; report each problem with its line number and print the valid records.
Solution
main.cpp
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
struct ValidationError : std::runtime_error { using std::runtime_error::runtime_error; };
struct Person { std::string name; int age; };
Person parse(const std::string& line) {
std::istringstream in(line);
Person p;
if (!(in >> p.name)) throw ValidationError("missing name");
std::string age;
if (!(in >> age)) throw ValidationError("missing age for " + p.name);
std::size_t used = 0;
try { p.age = std::stoi(age, &used); } catch (const std::logic_error&) { throw ValidationError("age '" + age + "' is not a number"); }
if (used != age.size()) throw ValidationError("age '" + age + "' is not a number");
if (p.age < 1 || p.age > 120) throw ValidationError("age " + age + " out of range");
return p;
}
int main() {
std::vector<Person> people;
std::string line;
int n = 0;
while (std::getline(std::cin, line)) {
++n;
try { people.push_back(parse(line)); }
catch (const ValidationError& e) { std::cout << "line " << n << ": " << e.what() << '\n'; }
}
for (const auto& p : people) std::cout << p.name << " (" << p.age << ")\n";
return 0;
}
Output Verified by compiling and running
line 2: missing age for Ravi
line 3: age '2x' is not a number
line 4: age 130 out of range
line 5: missing name
Asha (21)
Zoya (34)
parse() focuses on detecting problems; the loop decides to report and continue. std::stoi's own exceptions are translated into ValidationError with a friendlier message.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!