通讯录(纯C语言实现)
发布人:shili8
发布时间:2024-12-23 23:49
阅读次数:0
**通讯录系统**
本项目是一个简单的通讯录系统,使用C语言编写。该系统支持添加、删除、修改和查询联系人信息。
### **结构设计**
为了实现上述功能,我们需要定义一个结构来存储联系人的信息:
ctypedef struct {
int id;
char name[50];
char phone[20];
char email[100];
} Contact;
其中,`id`是联系人唯一标识符,`name`、`phone`和`email`分别代表联系人的姓名、电话号码和电子邮件。
### **通讯录类**
我们定义一个名为 `ContactBook` 的类来管理联系人信息:
ctypedef struct {
Contact* contacts;
int size;
} ContactBook;
其中,`contacts`是存储联系人的数组,`size`表示当前联系人数量。
### **函数实现**
下面是通讯录系统的主要功能函数:
#### **添加联系人**
cvoid addContact(ContactBook* book, Contact contact) {
// 检查是否已满 if (book->size >= MAX_CONTACTS) {
printf("联系人数量已达上限
");
return;
}
// 添加新联系人 book->contacts[book->size] = contact;
book->size++;
}
#### **删除联系人**
cvoid deleteContact(ContactBook* book, int id) {
// 检查是否存在 for (int i =0; i < book->size; i++) {
if (book->contacts[i].id == id) {
// 移除联系人 for (int j = i; j < book->size -1; j++) {
book->contacts[j] = book->contacts[j +1];
}
book->size--;
return;
}
}
printf("不存在该联系人
");
}
#### **修改联系人**
cvoid modifyContact(ContactBook* book, int id, Contact contact) {
// 检查是否存在 for (int i =0; i < book->size; i++) {
if (book->contacts[i].id == id) {
// 修改联系人信息 book->contacts[i] = contact;
return;
}
}
printf("不存在该联系人
");
}
#### **查询联系人**
cvoid queryContact(ContactBook* book, int id) {
// 检查是否存在 for (int i =0; i < book->size; i++) {
if (book->contacts[i].id == id) {
printf("姓名:%s
", book->contacts[i].name);
printf("电话:%s
", book->contacts[i].phone);
printf("电子邮件:%s
", book->contacts[i].email);
return;
}
}
printf("不存在该联系人
");
}
### **测试**
cint main() {
ContactBook book = {0};
Contact contact1 = {1, "张三", "12345678901", "zhangsan@example.com"};
Contact contact2 = {2, "李四", "98765432100", "lisi@example.com"};
addContact(&book, contact1);
addContact(&book, contact2);
queryContact(&book,1);
deleteContact(&book,1);
modifyContact(&book,2, (Contact){2, "王五", "12345678901", "wangwu@example.com"});
queryContact(&book,2);
return0;
}
上述代码演示了通讯录系统的基本功能,包括添加、删除、修改和查询联系人信息。

