-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10-7.cpp
76 lines (54 loc) · 1.53 KB
/
10-7.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <istream>
#include <fstream>
#include <string>
using namespace std;
class Employee {
friend ostream& operator<< // These have to be friends
(ostream& out, const Employee& emp); // so they can access
friend istream& operator>> // nonpublic members
(istream& in, Employee& emp);
public:
Employee( ) {}
~Employee( ) {}
void setFirstName(const string& name) {firstName_ = name;}
void setLastName(const string& name) {lastName_ = name;}
private:
string firstName_;
string lastName_;
};
// Send an Employee object to an ostream...
ostream& operator<<(ostream& out, const Employee& emp) {
out << emp.firstName_ << endl;
out << emp.lastName_ << endl;
return(out);
}
// Read an Employee object from a stream
istream& operator>>(istream& in, Employee& emp) {
in >> emp.firstName_;
in >> emp.lastName_;
return(in);
}
int main( ) {
Employee emp;
string first = "William";
string last = "Shatner";
emp.setFirstName(first);
emp.setLastName(last);
ofstream out("tmp\\emp.txt");
if (!out) {
cerr << "Unable to open output file.\n";
exit(EXIT_FAILURE);
}
out << emp; // Write the Emp to the file
out.close( );
ifstream in("tmp\\emp.txt");
if (!in) {
cerr << "Unable to open input file.\n";
exit(EXIT_FAILURE);
}
Employee emp2;
in >> emp2; // Read the file into an empty object
in.close( );
cout << emp2;
}