注意:分别用test.c(主函数),contact.c(函数实现),contact,h(函数声明)实现代码
test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "contact.h"
void menu()
{
printf("*******************************************************\n");
printf("********1. add 2.del ****************************\n");
printf("********3. search 4.modify****************************\n");
printf("********5. show 6.sort ****************************\n");
printf("********0. ****************************\n");
printf("*******************************************************\n");
}
int main()
{
int input = 0;
//创建通讯录
struct Contact con;//con就是通讯录,里面包含1000个元素的数组和size
InitContact(&con);//传地址才能真正改掉里面的数组和size
do
{
menu();
printf("请选择:>");
scanf("%d", &input);
switch (input)
{
case 1:
AddContact(&con);//必须知道通讯录里面有多少信息,才知道从哪里开始放
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
ShowContact(&con);
break;
case 6:
break;
case 0:
printf("退出通讯录");
break;
default:
printf("选择错误,请重新选择\n");
break;
}
} while (input);
return 0;
}
contact.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "contact.h"
void InitContact(struct Contact* ps)
{
memset(ps->data, 0, sizeof(ps->data));
ps->size = 0;//设置通讯录最初只有0个元素
}
void AddContact(struct Contact* ps)
{
if (ps->size == MAX)
{
printf("通讯录已满,无法增加");
}
else
{
printf("请输入名字:>");
scanf("%s", ps->data[ps->size].name);
printf("请输入年龄:>");
scanf("%s", &(ps->data[ps->size].age));
printf("请输入性别:>");
scanf("%s", ps->data[ps->size].sex);
printf("请输入电话:>");
scanf("%s", ps->data[ps->size].tele);
printf("请输入地址:>");
scanf("%s", ps->data[ps->size].addr);
ps->size++;
printf("添加成功\n");
}
}
void ShowContact(const struct Contact* ps)
{
if (ps->size == 0)
{
printf("通讯录为空");
}
else
{
int i = 0;
printf("%-20s\t%-4s\t%-5s\t%-12s\t %-20s\n", "名字", "年龄", "性别", "电话", "地址");
for (i = 0; i < ps->size; i++)
{
printf("%-20s\t%-4d\t%-5s\t%-12s\t %-20s\n", ps->data[i].name, ps->data[i].age,ps->data[i].sex,ps->data[i].tele, ps->data[i].addr);
}
}
}
contact.h
#pragma once
#define MAX 1000
#define MAX_NAME 20
#define MAX_SEX 5
#define MAX_TELE 12
#define MAX_ADDR 30
#include<stdio.h>
#include<string.h>
struct PeoInfo
{
char name[MAX_NAME];
int age;
char sex[MAX_SEX];
char tele[MAX_TELE];
char addr[MAX_ADDR];
};
//通讯录的类型
struct Contact
{
int size;//记录当前已经有的元素个数
struct PeoInfo data[MAX];//存放1000个人的信息
};
//声明函数
void InitContact(struct Contact* ps);
void AddContact(struct Contact* ps);
void ShowContact(const struct Contact* ps);//只是为了显示,而不改变,所以加const