Skip to content

Commit 1950093

Browse files
committed
added drill20 for chapter13
1 parent e735eb4 commit 1950093

File tree

4 files changed

+63
-0
lines changed

4 files changed

+63
-0
lines changed

Chapter13/README.md

+3
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,6 @@ Modify `>>` and `<<` to work with the redefined `Person`.
6161

6262
## [Drill 19](drill/19)
6363
Modify the constructor to check that `age` is [0:150) and that `name` doesn't contain any of the characters `;:"'[]*&^%$#@!`. Use `error()` in case of error. Test.
64+
65+
## [Drill 20](drill/20)
66+
Read a sequence of `Person`s from input (`cin`) into a `vector<Person>`; write them out again to the screen (`cout`). Test with correct and erroneous input.

Chapter13/drill/20/Person.cpp

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#include "Person.h"
2+
3+
std::istream& operator>>(std::istream& is, Person& rhs) {
4+
std::string name;
5+
int age = 0;
6+
if (is >> name >> age)
7+
rhs = Person{name, age};
8+
return is;
9+
}
10+
11+
std::ostream& operator<<(std::ostream& os, const Person& rhs) {
12+
return os << rhs.name() << ' ' << rhs.age();
13+
}

Chapter13/drill/20/Person.h

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#ifndef PERSON_H
2+
#define PERSON_H
3+
4+
#include <string>
5+
#include <iostream>
6+
#include <stdexcept>
7+
8+
class Person {
9+
public:
10+
Person() {}
11+
Person(const std::string& s, int i)
12+
: n{s}, a{i}
13+
{
14+
static const std::string illegal{";:\"'[]*&^%$#@!"};
15+
if (n.find_first_of(illegal) != std::string::npos)
16+
throw std::runtime_error{"name contains invalid characters"};
17+
if (a < 0 || a > 149)
18+
throw std::runtime_error{"invalid age"};
19+
}
20+
21+
std::string name() const { return n; }
22+
int age() const { return a; }
23+
private:
24+
std::string n;
25+
int a;
26+
};
27+
28+
std::istream& operator>>(std::istream&, Person&);
29+
std::ostream& operator<<(std::ostream&, const Person&);
30+
31+
#endif

Chapter13/drill/20/main.cpp

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#include "Person.h"
2+
3+
#include <iostream>
4+
#include <vector>
5+
#include <utility>
6+
7+
int main() {
8+
std::vector<Person> persons;
9+
std::cout << "Enter people:\n";
10+
for (Person p; std::cin >> p; )
11+
persons.push_back(std::move(p));
12+
13+
std::cout << "\nPeople:\n";
14+
for (const Person& p : persons)
15+
std::cout << p << '\n';
16+
}

0 commit comments

Comments
 (0)