Address Book
Address Book
tel.h
1
2
3
4
5
#ifndef TEL_H
#define TEL_H
// $Id: structuur2.tex,v 1.26 2008/09/02 11:51:15 dvermeir Exp
#include <string>
#include <iostream>
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
tel.C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
-----
19
20
21
22
#include
#include
#include
#include
<iterator>
<fstream>
<set>
"tel.h"
23
24
25
26
27
28
std::ostream&
operator<<(std::ostream& os, const TelRecord& r) {
os << r.name_ << \t << r.info_ << std::endl;
return os;
}
29
30
31
32
33
34
35
36
std::istream&
operator>>(std::istream& is, TelRecord& r) {
is >> r.name_ ; // line starts with name
is.ignore(); // ignore \t following name
std::getline(is, r.info_); // rest of line is info
return is;
}
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
int
main (int argc, char *argv[]) {
record_set dir;
{ // Load the database into a record_set
std::ifstream data_file(database_name);
if (data_file)
std::copy(
record_input_it(data_file),
record_input_it(),
std::inserter(dir, dir.begin())
);
}
// data_files is automatically closed by the ifstream destruc
57
58
59
60
61
62
63
switch (argc) {
// no arguments: just show all records on std::cout
case 1:
copy( dir.begin(), dir.end(),
std::ostream_iterator<TelRecord>(std::cout)
);
return 0;
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
if (r!=dir.end()) {
// success: iterator points to found record
std::cout << *r; // output it
return 0;
}
else {
std::cerr << "\"" << key
<< "\" not found" << std::endl;
return 1;
}
}
break;
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
if (info.size()==0) { // delete
if (dir.erase(r)!=1) {
// set::erase() returns number of deleted elements
std::cerr << "\"" << key
<< "\" not found; cannot erase" << std::endl;
return 3;
}
}
else { // insert or replace
std::pair<record_set::iterator, bool> pair =
dir.insert(r);
if (!pair.second) { // insert failed: duplicate key
dir.erase(pair.first); // erase,
dir.insert(r); // then insert again
}
}
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123