题目:写一个通讯录,要求具有查找,添加,删除,清空和显示的功能。
1.contact.h的实现
#define MAX 1000
#define NAME_LENGTH 20
#define SEX_LENGTH 5
#define TELE_LENGTH 20
#define ADDR_LENGTH 30
struct PeoInfo
{
char name[NAME_LENGTH];
char sex[SEX_LENGTH];
int age;
char tele[TELE_LENGTH];
char addr[ADDR_LENGTH];
};
struct Contacts
{
struct PeoInfo person[MAX];
int user_count;
};
typedef struct Contacts *pCon;
int add(pCon p);
int dele(pCon p);
int clear(pCon p);
int find(pCon p);
int modify(pCon p);
void show(pCon p);
2.contact.c的实现
#include<stdio.h>
#include"contacts.h"
#include<string.h>
//添加联系人操作
int add(pCon p)
{
if(p->user_count==MAX)
{
printf("contacts are full\n");
return -1;
}
printf("Please input the name:\n");
scanf("%s",p->person[p->user_count].name);
printf("Please input the sex:\n");
scanf("%s",p->person[p->user_count].sex);
printf("Please input the age:\n");
scanf("%d",&(p->person[p->user_count].age));
printf("Please input the tele:\n");
scanf("%s",p->person[p->user_count].tele);
printf("Please input the addr:\n");
scanf("%s",p->person[p->user_count].addr);
p->user_count++;
return 1;
}
//查找联系人操作
int find(pCon p)
{
char name[NAME_LENGTH];
int i = 0;
printf("Please input the name:");
scanf("%s",name);
for(i=0;i <p->user_count;i++)
{
if(strcmp(p->person[i].name ,name) == 0)
{
return i;
}
}
return -1;
}
//删除联系人操作
int dele(pCon p)
{
int i=0;
int user=find(p);
if(user!=-1)
{
for(i=user;i<p->user_count-1;i++)//如果此处是i<user_cuont那么下一行person[i+1]就越界,因为person数组最大元素为person[user_count-1]
{
p->person[i]=p->person[i+1];
}
p->user_count--;//删除以后少了一个联系人,联系人总数应该减一
return 1;
}
else
printf("no exist\n");
return -1;
}
//清空联系人操作
int clear(pCon p)
{
p->user_count=0;
return 1;
}
//修改联系人操作
int modify(pCon p)
{
int user=find(p);
if(user!=-1)
{
printf("please input the new name:");
scanf("%s",p->person[user].name);
printf("please input the new sex:");
scanf("%s",p->person[user].sex);
printf("please input new age:");
scanf("%s",p->person[user].age);
printf("please input new tele:");
scanf("%s",p->person[user].tele);
printf("please input new addr:");
scanf("%s",p->person[user].addr);
return 1;
}
else
printf("no exist\n");
return -1;
}
//显示通讯录的操作
void show(pCon p)
{
int i = 0;
printf("\tname\tsex\tage\ttele\taddr\n");
for(i = 0;i < p->user_count;i++)
{
printf("%10s\t",p->person[i].name);
printf("%5s\t",p->person[i].sex);
printf("%5d\t",p->person[i].age);
printf("%15s\t",p->person[i].tele);
printf("%30s\t",p->person[i].addr);
}
}
3.main.c的实现
#include<stdio.h>
#include"contacts.h"
int main()
{
int n=0;
struct Contacts *p1;
printf("Please input:");
scanf("%d",&n);
switch(n)
{
case 1:
add(p1);
break;
case 2:
dele(p1);
break;
case 3:
clear(p1);
break;
case 4:
find(p1);
break;
case 5:
modify(p1);
break;
case 6:
show(&p1);
break;
case 7:
return 0;
break;
default:
printf("error!\n");
break;
}
return 0;
}
总结:本题通讯录的实现主要是通过结构体来实现的,再运用结构体的指针来访问结构体内部的各个成员。同时还运用了switch函数来选择用户想要进行的操作。