您的位置:首页 > 编程语言 > C语言/C++

C++ 控制台简单电话本实现

2014-11-05 20:40 330 查看
<span style="font-family:Courier New;font-size:14px;">#include<iostream>
#include<fstream>
#include<string>
using namespace std;

class People
{
private:
string name;
string tel;
public:
People(){}
void setName(string _name){name=_name;}
void setTel(string _tel){tel=_tel;}
string getName(){return name;}
string getTel(){return tel;}
};

class Contact
{
private:
People people[100];
int count;
public:
Contact()
{
count=0;
readfile();
if(count==0)add();
int choice=-1;
while (choice!=0){
cout<<endl<<endl;
showName();
menu();
cin>>choice;
switch(choice){
case 0 :save();break;
case 1 :{
cout<<"Name:";
string _name;
cin>>_name;
int position=search(_name);
if(position!=-1)cout<<"tel:"<<people[position].getTel()<<endl;break;
}
case 2 :add();break;
case 3 :{
cout<<"Name:";
string _name;
cin>>_name;
del(_name);break;
}
default:break;
}

}
}
void menu()
{
cout<<"\t\t*************** Contact ***************\n";
cout<<"\t\t               1.search                \n";
cout<<"\t\t               2.add                   \n";
cout<<"\t\t               3.del                   \n";
cout<<"\t\t               0.exit                  \n";
cout<<"please input 0-3:\n";
}
int search(string _name)
{
int i;
for(i=0;i<count;i++){
if(_name==people[i].getName()){
return i;
}
}
if(i==count){
cout<<"can't find."<<endl;
return -1;
}
}
void add()
{
char ch;
while(true){
string _name,_tel;
cout<<"Name:";
cin>>_name;people[count].setName(_name);
cout<<"Tel:";
cin>>_tel;people[count].setTel(_tel);
count++;
cout<<"continue?	y/n    ";
cin>>ch;
if(ch=='n')break;
}
}
void del(string _name)
{
int position;
position=search(_name);
if(position!=-1){
for(int i=position;i<count;i++){
people[i]=people[i+1];
}
count--;
}
}
void save()
{
ofstream write("data.txt",ios::out);
if(!write){
cerr<<"open error!"<<endl;
exit(1);
}
for(int i=0;i<count;i++){
write<<people[i].getName();
write<<" ";
write<<people[i].getTel();
if(i<count-1)write<<endl;
}
write.close();
}
void showName()
{
for(int i=0;i<count;i++){
cout<<people[i].getName()<<endl;
}
}
void readfile()
{
ifstream read("data.txt",ios::in);
if(read){
while(!read.eof()){
string _name,_tel;
read>>_name>>_tel;
people[count].setName(_name);
people[count].setTel(_tel);
count++;
}

}
else{
//cerr<<"open error!"<<endl;
//exit(1);
}

read.close();
}
};

int main()
{
Contact contact;
return 0;
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: