c语言通讯录代码
时间: 2023-08-01 07:11:09 浏览: 84
c语言通讯录代码完美实现
下面是一份简单的 C 语言通讯录代码,使用结构体实现:
```c
#include <stdio.h>
#include <string.h>
#define MAX_CONTACTS 100
struct Contact {
char name[50];
char email[50];
char phone[15];
};
int main() {
struct Contact contacts[MAX_CONTACTS];
int num_contacts = 0;
while (1) {
printf("\nMenu:\n");
printf("1. Add contact\n");
printf("2. List contacts\n");
printf("3. Search contact\n");
printf("4. Exit\n");
int choice;
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1: {
if (num_contacts >= MAX_CONTACTS) {
printf("Error: Maximum contacts reached.\n");
break;
}
struct Contact new_contact;
printf("\nEnter name: ");
scanf("%s", new_contact.name);
printf("Enter email: ");
scanf("%s", new_contact.email);
printf("Enter phone: ");
scanf("%s", new_contact.phone);
contacts[num_contacts] = new_contact;
num_contacts++;
printf("\nContact added successfully.\n");
break;
}
case 2: {
if (num_contacts == 0) {
printf("No contacts found.\n");
break;
}
printf("\nContacts:\n");
for (int i = 0; i < num_contacts; i++) {
printf("%d. Name: %s\n", i + 1, contacts[i].name);
printf(" Email: %s\n", contacts[i].email);
printf(" Phone: %s\n", contacts[i].phone);
}
break;
}
case 3: {
if (num_contacts == 0) {
printf("No contacts found.\n");
break;
}
char search_name[50];
printf("\nEnter name to search for: ");
scanf("%s", search_name);
int found = 0;
for (int i = 0; i < num_contacts; i++) {
if (strcmp(contacts[i].name, search_name) == 0) {
printf("\nContact found:\n");
printf("Name: %s\n", contacts[i].name);
printf("Email: %s\n", contacts[i].email);
printf("Phone: %s\n", contacts[i].phone);
found = 1;
break;
}
}
if (!found) {
printf("\nContact not found.\n");
}
break;
}
case 4: {
printf("\nExiting program.\n");
return 0;
}
default: {
printf("\nInvalid choice. Try again.\n");
break;
}
}
}
}
```
该代码定义了一个 `Contact` 结构体,包含联系人的姓名、电子邮件和电话号码。使用一个数组来存储多个联系人,最大数量为 `MAX_CONTACTS`。`main` 函数中使用一个无限循环来提示用户选择菜单选项。根据用户选择的选项,执行不同的操作:添加联系人,列出联系人列表,搜索联系人或退出程序。
阅读全文