contact.h
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<assert.h>
#define MAX_NUMPERSON 10
typedef struct PersonInfo
{
char name[20];
char sex[20];
int age;
char tele[20];
char addr[20];
}PersonInfo;
typedef struct Contact
{
int usedSize;
PersonInfo per[MAX_NUMPERSON];
}Contact;
void InitContact(Contact *pCon);
void AddContact(Contact *pCon);
//找到返回下标 找不到返回-1 姓名查找
int SearchContact(Contact *pCon);
void DelContact(Contact *pCon);
void ShowContact(Contact *pCon);
void ClearContact(Contact *pCon);
void DestroyContact(Contact *pCon);
contact.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"contact.h"
void InitContact(Contact *pCon)
{
assert(pCon != NULL);
pCon->usedSize = 0;
对数组进行初始化
memset(pCon->per, 0, sizeof(pCon->per));
}
void AddContact(Contact *pCon)
{
if (pCon->usedSize == MAX_NUMPERSON)
{
printf("不好意思老铁,通讯录满了\n");
return;
}
printf("请输入姓名:");
scanf("%s", pCon->per[pCon->usedSize].name);
printf("请输入性别:");
scanf("%s", pCon->per[pCon->usedSize].sex);
printf("请输入年龄:");
scanf("%d", &(pCon->per[pCon->usedSize].age));
printf("请输入电话:");
scanf("%s", pCon->per[pCon->usedSize].tele);
printf("请输入地址:");
scanf("%s", pCon->per[pCon->usedSize].addr);
pCon->usedSize++;
printf("添加成功\n");
}
//找到返回下标 找不到返回-1 姓名查找
int SearchContact(Contact *pCon)
{
int i = 0;
char name[20];
if (pCon->usedSize == 0)
{
printf("通讯录为空\n");
return -1;
}
printf("请输入姓名:");
scanf("%s", name);
for (i = 0; i < pCon->usedSize; i++)
{
if (strcmp(pCon->per[i].name, name) == 0)
{
return i;
}
}
return -1;
}
void DelContact(Contact *pCon)
{
int index = SearchContact(pCon);
int i = 0;
if (index == -1)
{
printf("查无此人\n");
return;
}
//删除
for (i = index; i < pCon->usedSize - 1; i++)
{
pCon->per[i] = pCon->per[i + 1];
}
pCon->usedSize--;
printf("删除成功\n");
}
void ShowContact(Contact *pCon)
{
int i = 0;
printf("%-20s %-10s %-10s %-11s %-15s\n", "姓名", "性别", "年龄", "电话", "地址");
for (i = 0; i < pCon->usedSize; i++)
{
printf("%-20s %-10s %-10d %-11s %-15s\n", pCon->per[i].name,
pCon->per[i].sex, pCon->per[i].age, pCon->per[i].tele, pCon->per[i].addr);
}
}
void ClearContact(Contact *pCon)
{
pCon->usedSize = 0;
}
text.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"contact.h"
void menu()
{
printf("*********1.add ***********2.search ***********\n");
printf("*********3.del ***********4.show ***********\n");
printf("*********5.clear***********6.Destroy***********\n");
printf("*********0.exit *******************************\n");
}
void start()
{
int input = 0;
//初始化通讯录 数组 usedSize
Contact con;
InitContact(&con);
do
{
menu();
printf("请输入你的操作>>");
scanf("%d", &input);
switch (input)
{
case 1:
AddContact(&con);
break;
case 2:
SearchContact(&con);
break;
case 3:
DelContact(&con);
break;
case 4:
ShowContact(&con);
break;
case 5:
ClearContact(&con);
break;
}
} while (input);
}
int main()
{
start();
return 0;
}