📄 222.cpp
字号:
#include <iostream>
#include <iomanip>
#include <fstream>
#define SIZE 50
using namespace std;
void search(void);
void creat(void);
int find(char[],char[],int,int);
main()
{
int judge;
ofstream phonebook("phonebook.txt");
//初始化
phonebook<<"hupeipei "<<" 15810538683"<<endl;
phonebook<<"niuxinli "<<" 15810538681"<<endl;
cout<<"请输入命令,1为查找用户;2为删除或创建用户\n";
cin>>judge;
if(judge==1)
search();
else
creat();
phonebook.close();
system("pause");
}
//创建和删除函数
void creat(void)
{
fstream phonebook("phonebook.txt");
int x;
cout<<"1为创建用户,2为删除用户\n";
cin>>x;
if(x==1)
{
int num;
char ch[SIZE];
cout<<"请您输入要创建人的姓名:\n";
int i=0;
cin>>ch[i];
i++;
while(ch[i-1]!='#')
{
cin>>ch[i];
i++;
}
//将所有的字符读到string中
int m=0;
char chch,string[SIZE];
while(phonebook.good())
{
phonebook.get(chch);
string[m]=chch;
m++;
}
fstream phonebook("phonebook.txt");
phonebook.seekg(m-1);
phonebook<<endl;
int j=0;
for(j=0;j<=i-2;j++)
phonebook<<ch[j];
phonebook<<"\t";
cout<<"请您输入要创建人的电话号码:\n";
cin>>num;
phonebook<<num<<endl;
}
else
{
cout<<"请您输入要删除人的姓名:\n";
char ch[SIZE];
int i=0;
cin>>ch[i];
i++;
while(ch[i-1]!='#')
{
cin>>ch[i];
i++;
}
char chch,string[SIZE];
char ch1[i-1];
//ch1中存放要查找的姓名
int k=0;
for(k=0;k<=i-2;k++)
{
ch1[k]=ch[k];
}
//将所有的字符读到longch中
i=0;
while(phonebook.good())
{
phonebook.get(chch);
string[i]=chch;
i++;
}
//调用查找函数
int userposition;
userposition=find(string,ch1,i,k);
int n=userposition;
if(n>=0)
{
while(string[n]!='\n')
{
n++;
}
char temp[i-n+userposition];
k=0;
for(k=0;k<=userposition-2;k++)
temp[k]=string[k];
for(k=userposition-1;k<=i-n+userposition-2;k++)
temp[k]=string[k+n-userposition];
ofstream phonebook("phonebook.txt");
int j=0;
for(j=0;j<=i-n+userposition-2;j++)
phonebook<<temp[j];
}
else
cout<<"查无此用户\n";
}
phonebook.close();
}
//查找函数
void search(void)
{
fstream phonebook("phonebook.txt");
char ch[SIZE],chch,string[SIZE];
cout<<"请输入要查找人的姓名(以#结束):\n";
int i=0;
cin>>ch[i];
i++;
while(ch[i-1]!='#')
{
cin>>ch[i];
i++;
}
char ch1[i-1];
int k=0;
for(k=0;k<=i-2;k++)
{
ch1[k]=ch[k];
}//ch1中存放要查找的姓名
i=0;
while(phonebook.good()){
phonebook.get(chch);
string[i]=chch;
i++;
}//将所有的字符读到longch中
//调用查找函数
int userposition;
userposition=find(string,ch1,i,k);
i=userposition;
if(i>=0){
while(string[i]!='\n')
{
cout<<string[i];
i++;
}
cout<<endl;
}
else
cout<<"查无此用户\n";
}
//查找函数
int find(char string1[],char string2[],int size1,int size2)
{
int i=0,j=0,control=0,position=-1;/*初始化*/
while(i<size1&&j<size2)
{
if(string1[i]==string2[j])
{
control++;/*计数器累加*/
if(control==1)/*第一次匹配时用position保存下标*/
position=i;
i++;
j++;/*看下一个是否匹配*/
}
else{
j=0;/*回到第二个字符串的首字符*/
control=0;/*计数器清零*/
if(position==-1)/*未匹配时直接向下查找*/
i++;
else{
i=position+1;/*匹配是从保存下标的下一个开始查找*/
position=-1;/*地址清零*/
}
}
}
if(control==size2) /*计数器与size2相等时,表明找到,返回下标*/
return position;
else
return -1; /*未找到返回-1*/
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -