Skip to content

Commit 062d5f2

Browse files
committed
added drill21 for chapter13
1 parent 1950093 commit 062d5f2

File tree

4 files changed

+72
-0
lines changed

4 files changed

+72
-0
lines changed

Chapter13/README.md

+3
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,6 @@ Modify the constructor to check that `age` is [0:150) and that `name` doesn't co
6464

6565
## [Drill 20](drill/20)
6666
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.
67+
68+
## [Drill 21](drill/21)
69+
Change the representation of `Person` to have `first_name` and `second_name` instead of `name`. Make it an error not to supply both a first and a second name. Be sure to fix `>>` and `<<` also. Test.

Chapter13/drill/21/Person.cpp

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

Chapter13/drill/21/Person.h

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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& s1, const std::string& s2, int i)
12+
: fn{s1}, ln{s2}, a{i}
13+
{
14+
static const std::string illegal{";:\"'[]*&^%$#@!"};
15+
if (fn.find_first_of(illegal) != std::string::npos)
16+
throw std::runtime_error{"first name contains invalid characters"};
17+
if (ln.find_first_of(illegal) != std::string::npos)
18+
throw std::runtime_error{"last name contains invalid characters"};
19+
if (a < 0 || a > 149)
20+
throw std::runtime_error{"invalid age"};
21+
}
22+
23+
std::string first_name() const { return fn; }
24+
std::string last_name() const { return ln; }
25+
int age() const { return a; }
26+
private:
27+
std::string fn;
28+
std::string ln;
29+
int a;
30+
};
31+
32+
std::istream& operator>>(std::istream&, Person&);
33+
std::ostream& operator<<(std::ostream&, const Person&);
34+
35+
#endif

Chapter13/drill/21/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)