使用c++写一个通讯录系统
时间: 2023-05-12 16:04:19 浏览: 178
C++写的通讯录系统
好的,我可以为您提供一个使用 C 语言编写的通讯录系统的基本框架。首先,您需要定义一个结构体来存储每个联系人的信息,例如姓名、电话号码、电子邮件地址等。然后,您可以使用链表来存储所有联系人的信息,并实现一些基本的操作,例如添加、删除、查找和显示联系人等。以下是一个简单的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
#define MAX_PHONE_LEN 15
#define MAX_EMAIL_LEN 30
typedef struct contact {
char name[MAX_NAME_LEN];
char phone[MAX_PHONE_LEN];
char email[MAX_EMAIL_LEN];
struct contact *next;
} Contact;
Contact *head = NULL;
void add_contact() {
Contact *new_contact = (Contact *) malloc(sizeof(Contact));
printf("Enter name: ");
scanf("%s", new_contact->name);
printf("Enter phone number: ");
scanf("%s", new_contact->phone);
printf("Enter email address: ");
scanf("%s", new_contact->email);
new_contact->next = head;
head = new_contact;
printf("Contact added successfully!\n");
}
void delete_contact() {
char name[MAX_NAME_LEN];
printf("Enter name to delete: ");
scanf("%s", name);
Contact *prev = NULL;
Contact *curr = head;
while (curr != NULL) {
if (strcmp(curr->name, name) == 0) {
if (prev == NULL) {
head = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
printf("Contact deleted successfully!\n");
return;
}
prev = curr;
curr = curr->next;
}
printf("Contact not found!\n");
}
void search_contact() {
char name[MAX_NAME_LEN];
printf("Enter name to search: ");
scanf("%s", name);
Contact *curr = head;
while (curr != NULL) {
if (strcmp(curr->name, name) == 0) {
printf("Name: %s\n", curr->name);
printf("Phone: %s\n", curr->phone);
printf("Email: %s\n", curr->email);
return;
}
curr = curr->next;
}
printf("Contact not found!\n");
}
void display_contacts() {
Contact *curr = head;
while (curr != NULL) {
printf("Name: %s\n", curr->name);
printf("Phone: %s\n", curr->phone);
printf("Email: %s\n", curr->email);
curr = curr->next;
}
}
int main() {
int choice;
while (1) {
printf("1. Add contact\n");
printf("2. Delete contact\n");
printf("3. Search contact\n");
printf("4. Display contacts\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_contact();
break;
case 2:
delete_contact();
break;
case 3:
search_contact();
break;
case 4:
display_contacts();
break;
case 5:
exit(0);
default:
printf("Invalid choice!\n");
}
}
return 0;
}
```
这个通讯录系统包括添加、删除、查找和显示联系人等基本操作。您可以根据自己的需求进行修改和扩展。
阅读全文