forked from jihao/AddressBook
-
Notifications
You must be signed in to change notification settings - Fork 3
/
addressbook.cpp
132 lines (117 loc) · 2.7 KB
/
addressbook.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include "addressbook.h"
AddressBook::AddressBook():isQuit(0)
{
char buf[256]="";
Contact c;
ifstream ifs;
ifs.exceptions (ifstream::failbit | ifstream::badbit );
try
{
ifs.open("contact.txt",ifstream::in);
while(ifs.peek()!=EOF)
{
ifs.getline(buf,255);
c.name.append(buf);
ifs.getline(buf,255);
c.number.append(buf);
ifs.getline(buf,255);
c.address.append(buf);
contact.push_back(c);
c.name.clear();
c.number.clear();
c.address.clear();
}
ifs.close();
}
catch(std::ifstream::failure e)
{
cerr << "Exception opening/reading/closing file\n";
cerr<<"The file contact.txt maybe don't exit or have been destroyed\n";
cerr<<"Please try to create file contact.txt again\n";
}
}
bool AddressBook::add(const Contact &c)
{
pList it;
//chech if the person have exited
if(search(c.name,it))
return false;
else
{
contact.push_back(c);
return true;
}
}
bool AddressBook::help()
{
cout<<"Input add----\tfor adding contact"<<endl;
cout<<"for example"<<endl;
cout<<"name: xiaoming"<<endl;
cout<<"mobile: 18888888888"<<endl;
cout<<"address: xiaoming jia"<<endl;
cout<<"address entry added"<<endl;
cout<<"Input search----\tfor searching contact"<<endl;
cout<<"Input delete----\tfor deleting contact"<<endl;
cout<<"Input !help----\tfor help"<<endl;
cout<<"Input !quit----\tfor quit"<<endl;
return true;
}
bool AddressBook::remove(const string &s)
{
pList it;
if(search(s,it))
{
pList it0=contact.end();
while(it!=it0)
{
it=contact.erase(it);
it=search(it,it0,s);
}
}
else
return false;
return true;
}
bool AddressBook::save(list<Contact> c)
{
Contact temp;
ofstream out("contact.txt",ofstream::trunc);
while(!contact.empty())
{
temp=contact.front();
out<<temp.name<<"\n";
out<<temp.number<<"\n";
out<<temp.address<<"\n";
contact.pop_front();
}
out.close();
}
bool AddressBook::search(const string &s,pList &r)
{
list<Contact>::iterator it1,it2;
if(contact.size()!=0)
{
it1=contact.begin();
it2=contact.end();
r=search(it1,it2,s);
if(r==it2)
return false;
else
return true;
}
else
return false;
}
pList AddressBook::search(pList b,pList e,const string &s)
{
for(;b!=e;b++)
{
if(b->isContact(s))
return b;
}
return e;
}
AddressBook::~AddressBook()
{
save(contact);
}