帮我用c语言写一个通讯录
时间: 2023-11-23 13:07:19 浏览: 61
用C语言写通讯录
好的,下面是一个简单的通讯录程序,可以添加、查找、删除联系人信息:
```c
#include <stdio.h>
#include <string.h>
#define MAX_NAME_LEN 20
#define MAX_PHONE_LEN 11
#define MAX_CONTACTS 100
struct Contact {
char name[MAX_NAME_LEN];
char phone[MAX_PHONE_LEN];
};
struct Contact contacts[MAX_CONTACTS];
int num_contacts = 0;
int add_contact() {
if (num_contacts >= MAX_CONTACTS) {
printf("Error: too many contacts\n");
return 0;
}
struct Contact c;
printf("Enter name: ");
scanf("%s", c.name);
printf("Enter phone: ");
scanf("%s", c.phone);
contacts[num_contacts++] = c;
printf("Added contact: %s, %s\n", c.name, c.phone);
return 1;
}
void find_contact() {
char name[MAX_NAME_LEN];
printf("Enter name to find: ");
scanf("%s", name);
for (int i = 0; i < num_contacts; i++) {
if (strcmp(contacts[i].name, name) == 0) {
printf("Found contact: %s, %s\n", contacts[i].name, contacts[i].phone);
return;
}
}
printf("Contact not found\n");
}
void delete_contact() {
char name[MAX_NAME_LEN];
printf("Enter name to delete: ");
scanf("%s", name);
for (int i = 0; i < num_contacts; i++) {
if (strcmp(contacts[i].name, name) == 0) {
for (int j = i; j < num_contacts-1; j++) {
contacts[j] = contacts[j+1];
}
num_contacts--;
printf("Deleted contact: %s, %s\n", name, contacts[i].phone);
return;
}
}
printf("Contact not found\n");
}
int main() {
int choice;
do {
printf("\n1. Add contact\n");
printf("2. Find contact\n");
printf("3. Delete contact\n");
printf("4. Quit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_contact();
break;
case 2:
find_contact();
break;
case 3:
delete_contact();
break;
case 4:
printf("Goodbye!\n");
break;
default:
printf("Invalid choice\n");
break;
}
} while (choice != 4);
return 0;
}
```
在这个程序中,我们使用了一个结构体Contact来表示联系人信息,使用一个静态数组contacts来存储所有联系人,使用一个变量num_contacts来记录当前有多少个联系人。程序提供了三个函数add_contact、find_contact和delete_contact来实现添加、查找和删除联系人信息。在主函数中,我们使用一个循环来不断读取用户的选择,直到用户选择退出程序。
阅读全文