数据结构与算法——简易通讯录

来源:互联网 发布:失业金数据与非农数据 编辑:程序博客网 时间:2024/06/06 00:50

主要实现模拟一个通信录的操作,通过命令删除通讯录、添加通讯录和查找某个人的电话号码。

原理很简单,就是单链表的删除、插入和查找的实现。

需要注意的是,输入的处理。要获取一行带有空格的字符串并将其赋值给一个string类变量,需先定义一个 char temp[1000] 数组,然后gets(temp),然后 string str = temp;

下面是代码:

#include <iostream>#include <string>#include <stdio.h>using namespace std;class record{//记录类public:string Name;int phoneNum;};record phonebook[1000]={"",-1};//通讯录数组class order{//命令类public:string opt;//命令操作符string name;//命令参数1int num;//命令参数2public:bool CheckOrder();//检查命令是否合法,合法返回真,不合法返回假};bool order::CheckOrder(){if(opt == "ClearContactBook"&&name==""&&num==-1)return true;else if(opt == "AddCard"&&name!=""&&num!=-1)return true;else if(opt == "SearchCard"&&name!=""&&num==-1)return true;else return false;}order input;//定义存储命令的对象int ClearBook(){for(int i=0;(phonebook[i].Name)!="";i++){phonebook[i].Name="";phonebook[i].phoneNum = -1;}return 0;}int AddContact(){int i=0;for(i=0;(phonebook[i].Name)!="";i++);phonebook[i].Name=input.name;phonebook[i].phoneNum = input.num;return 0;}int SearchContact(){int flag=0;for(int i=0;(phonebook[i].Name)!="";i++){if(phonebook[i].Name == input.name){cout<<phonebook[i].phoneNum<<endl;flag=1;}}if(!flag)cout<<-1<<endl;return 0;}int HandleOpt(order& input,int type)//处理命令的函数,type表示命令的类型,清除 0,加入 1,查找 2{switch(type){case 0:ClearBook();break;case 1:AddContact();break;case 2:SearchContact();break;default:break;}return 0;}int main(){input.opt = "";input.name = "";input.num = -1;string str;char temp[1000];char tmp[1000];string str1,str2,str3;int flag=0;int k=0;int i=0;int len=0;while(gets(temp)){str= temp;len=str.length();for(i=0;i<1000;++i)tmp[i]='\0';for(i=k;(str[i]!=' ');){tmp[i-k] = str[i];++i;if(i>=len) break;}k=i;tmp[k+1]='\0';input.opt = tmp;for(i=0;i<1000;++i)tmp[i]='\0';while((k<len)&&(str[k]==' '))k++;if(k<len){for(i=k;(str[i]!=' ');){tmp[i-k] = str[i];++i;if(i>=len) break;}k=i;tmp[i]='\0';str2=tmp;for(i=0;i<1000;++i)tmp[i]='\0';while((k<len)&&(str[k]==' '))k++;if(k<len){for(i=k;(str[i]!=' ');){tmp[i-k] = str[i];++i;if(i>=len) break;}k=i;tmp[i]='\0';str3=tmp;}}if((input.opt ==  "ClearContactBook")&&str2==""&&str3==""){if(input.CheckOrder())HandleOpt(input,0);else{cout<<"error:The system does not support this command"<<endl;}}else if(input.opt == "AddCard"&&str2!=""&&str3!=""){input.name = str2;input.num = atoi(tmp);if(input.CheckOrder()){HandleOpt(input,1);}else{cout<<"error:The system does not support this command"<<endl;}}else if(input.opt =="SearchCard" && str2!=""&&str3=="" ){input.name = str2;if(input.CheckOrder()){HandleOpt(input,2);}else{cout<<"error:The system does not support this command"<<endl;}}else{cout<<"error:The system does not support this command"<<endl;}str="";str1="";str2="";str3="";flag=0;k=0;i=0;for(int i=0;i<1000;i++)temp[i]='\0';tmp[i]='\0';input.opt="";input.name="";input.num=-1;}return 0;}



0 0
原创粉丝点击