1、写一个结构体数组用来记录信息
这里我写了一个可以存储一个人的姓名、电话、邮箱的结构体。
struct note{
char name[100];
char phone[100];
char mail[100];
}people[1000];
2、用文件储存更加方便
p=fopen("list.txt","r");
if(p==NULL)
{
fclose(p);
p=fopen("list.txt","w");
fclose(p);
}
3、写一个简单的界面(可以用死循环)
while(1)
{
n=0;
p=fopen("list.txt","r");
while(fscanf(p,"%s%s%s",people[n].name,people[n].phone,people[n].mail)!=EOF)
n++;
fclose(p);
///--------一次循环更新一次数据
4、写一个简单的查找程序
int k;
cout<<"输入1读取,输入2输入"<<endl;
cin>>k;
if(k==1)
{
cout<<"输入信息"<<endl;
char s[100];
cin>>s;
bool ok=0;
for(i=0;i<strlen(s);i++)
if(s[i]>='0'&&s[i]<='9')
ok=1;
//自动识别输入的是姓名还是电话号码
if(ok==0)
{
//cout<<"通过姓名找到联系人"<<endl;
//system("pause");
bool you=0;
for(i=0;i<n;i++)
if(strcmp(s,people[i].name)==0)
{
you=1;
cout<<"姓名"<<people[i].name<<endl;
cout<<"电话号码"<<people[i].phone<<endl;
cout<<"邮箱"<<people[i].mail<<endl;
}
if(you==0)
cout<<"没有通过姓名找到联系人"<<endl;
}
if(ok==1)
{
//cout<<"通过电话找联系人"<<endl;
//system("pause");
bool you=0;
for(i=0;i<n;i++)
if(strcmp(s,people[i].phone)==0)
{
you=1;
cout<<"姓名"<<people[i].name<<endl;
cout<<"电话号码"<<people[i].phone<<endl;
cout<<"邮箱"<<people[i].mail<<endl;
}
if(you==0)
cout<<"没有通过电话找到联系人"<<endl;
}
5、添加信息的代码
if(k==2)
{
p1=fopen("list.txt","a+");
char ss[1000];
cout<<"请输入姓名"<<endl;
cin>>ss;
fprintf(p1,"%s\n",ss);
cout<<"请输入电话"<<endl;
cin>>ss;
fprintf(p1,"%s\n",ss);
cout<<"请输入邮箱"<<endl;
cin>>ss;
fprintf(p1,"%s\n",ss);
fclose(p1);
}
}
最终的程序
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
FILE *p,*p1;
struct note{
char name[100];
char phone[100];
char mail[100];
}people[1000];
int main()
{
int n=0,i,j;
p=fopen("list.txt","r");
if(p==NULL)
{
fclose(p);
p=fopen("list.txt","w");
fclose(p);
}
while(1)
{
n=0;
p=fopen("list.txt","r");
while(fscanf(p,"%s%s%s",people[n].name,people[n].phone,people[n].mail)!=EOF)
n++;
fclose(p);
///---------------
int k;
cout<<"输入1读取,输入2输入"<<endl;
cin>>k;
if(k==1)
{
cout<<"输入信息"<<endl;
char s[100];
cin>>s;
bool ok=0;
for(i=0;i<strlen(s);i++)
if(s[i]>='0'&&s[i]<='9')
ok=1;
if(ok==0)
{
//cout<<"通过姓名找到联系人"<<endl;
//system("pause");
bool you=0;
for(i=0;i<n;i++)
if(strcmp(s,people[i].name)==0)
{
you=1;
cout<<"姓名"<<people[i].name<<endl;
cout<<"电话号码"<<people[i].phone<<endl;
cout<<"邮箱"<<people[i].mail<<endl;
}
if(you==0)
cout<<"没有通过姓名找到联系人"<<endl;
}
if(ok==1)
{
//cout<<"通过电话找联系人"<<endl;
//system("pause");
bool you=0;
for(i=0;i<n;i++)
if(strcmp(s,people[i].phone)==0)
{
you=1;
cout<<"姓名"<<people[i].name<<endl;
cout<<"电话号码"<<people[i].phone<<endl;
cout<<"邮箱"<<people[i].mail<<endl;
}
if(you==0)
cout<<"没有通过电话找到联系人"<<endl;
}
}
if(k==2)
{
p1=fopen("list.txt","a+");
char ss[1000];
cout<<"请输入姓名"<<endl;
cin>>ss;
fprintf(p1,"%s\n",ss);
cout<<"请输入电话"<<endl;
cin>>ss;
fprintf(p1,"%s\n",ss);
cout<<"请输入邮箱"<<endl;
cin>>ss;
fprintf(p1,"%s\n",ss);
fclose(p1);
}
}
return 0;
}