Skip to content

Commit f4cd242

Browse files
committed
added drill15 for chapter13
1 parent 4b7bf59 commit f4cd242

File tree

4 files changed

+40
-0
lines changed

4 files changed

+40
-0
lines changed

Chapter13/README.md

+3
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,6 @@ Define a `struct Person` containing a `string` name and an `int` age.
4646

4747
## [Drill 14](drill/14)
4848
Define a variable of type `Person`, initialize it with "Goofy" and 63, and write it to the screen (`cout`).
49+
50+
## [Drill 15](drill/15)
51+
Define an input (`>>`) and an output (`<<`) operator for `Person`; read in a `Person` from the keyboard (`cin`) and write it out to the screen (`cout`).

Chapter13/drill/15/Person.cpp

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

Chapter13/drill/15/Person.h

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#ifndef PERSON_H
2+
#define PERSON_H
3+
4+
#include <string>
5+
#include <iostream>
6+
7+
struct Person {
8+
std::string name;
9+
int age;
10+
};
11+
12+
std::istream& operator>>(std::istream&, Person&);
13+
std::ostream& operator<<(std::ostream&, const Person&);
14+
15+
#endif

Chapter13/drill/15/main.cpp

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#include "Person.h"
2+
3+
#include <iostream>
4+
5+
int main() {
6+
Person p;
7+
std::cout << "Enter person: ";
8+
if (std::cin >> p)
9+
std::cout << p << '\n';
10+
}

0 commit comments

Comments
 (0)