实现对通讯录的添加,删除,查询,全部输出以及存储的功能,使用vector简化操作
# include <iostream>
# include <string>
# include <vector>
using namespace std;
typedef struct {string name;string sex;string tel;string email;string address;} PEOPLE;
PEOPLE p[100];
int main() {vector<PEOPLE> vec;int a,n,b,i,flag;string m;char q;FILE *fp=fopen("tel.txt","rw");//打开原来的通讯录并且读入cout <<"*****************欢迎来到通讯录*****************"<<endl;cout <<" 选择操作 "<<endl;cout <<"1.添加 2.查询 3.删除 4.全部输出 5.保存此次所有操作"<<endl;i=0;char name[100],sex[10],tel[100],email[100],address[100];while(fscanf(fp,"%s %s %s %s %s",name ,sex ,tel ,email ,address )!=EOF) {p[i].name =name;p[i].sex =sex;p[i].tel =tel;p[i].email =email;p[i].address =address;vec.push_back(p[i]);//直接用p[i]读入会产生问题,所以借助char作为中间容器i++;};cin >>a;q='Y';while(q=='Y') {if(a==1) {cout << "输入添加的人数:"<< endl;cin >>n;b = vec.size();cout << b<<endl;for(i=0; i<n; i++) {cout << "输入姓名、性别、电话、邮箱、家庭住址"<<endl;cin >> p[i].name>>p[i].sex>>p[i].tel>>p[i].email>>p[i].address;vec.push_back(p[i]);}cout << vec.size();}if(a==2) {cout << "输入姓名:"<< endl;cin >> m;for(i=0; i<vec.size(); i++) {flag=1;if(vec[i].name==m) {flag=0;cout << vec[i].name << " "<< vec[i].sex << " "<< vec[i].tel << " "<< vec[i].email << " "<< vec[i].address <<endl;}}if(flag==1) {cout << "该用户不存在" <<endl;}}if(a==3) {cout << "输入姓名:"<< endl;cin >> m;for(vector<PEOPLE>::iterator Iter=vec.begin(); Iter!=vec.end();) {flag=1;if(Iter->name==m) {flag=0;Iter=vec.erase(Iter);//结构体正确删除操作cout << "删除成功"<<endl;break;} else {Iter++;}}if(flag==1) {cout << "该用户不存在" <<endl;}}if(a==4) {b=vec.size();for(i=0; i<b; i++) {cout << vec[i].name << " "<< vec[i].sex << " "<< vec[i].tel << " "<< vec[i].email << " "<< vec[i].address <<endl;}}if(a==5) {fclose(fp);b=vec.size();freopen("tel.txt","w",stdout);for(i=0; i<b; i++) {cout << vec[i].name << " "<< vec[i].sex << " "<< vec[i].tel << " "<< vec[i].email << " "<< vec[i].address <<endl;}return 0;}cout << "是否继续进行其他操作?请输入Y或N"<< endl;cin >> q;if(q=='Y') {cout << "选择操作:"<< endl;cin >> a;}}return 0;}
//结构体正确删除操作cout << "删除成功"<<endl;break;} else {Iter++;}}if(flag==1) {cout << "该用户不存在" <<endl;}}if(a==4) {b=vec.size();for(i=0; i<b; i++) {cout << vec[i].name << " "<< vec[i].sex << " "<< vec[i].tel << " "<< vec[i].email << " "<< vec[i].address <<endl;}}if(a==5) {fclose(fp);b=vec.size();freopen("tel.txt","w",stdout);for(i=0; i<b; i++) {cout << vec[i].name << " "<< vec[i].sex << " "<< vec[i].tel << " "<< vec[i].email << " "<< vec[i].address <<endl;}return 0;}cout << "是否继续进行其他操作?请输入Y或N"<< endl;cin >> q;if(q=='Y') {cout << "选择操作:"<< endl;cin >> a;}}return 0;}