用c语言写一个通讯录管理系统
时间: 2023-05-14 11:06:23 浏览: 85
c语言写的通讯录管理系统
4星 · 用户满意度95%
好的,我可以为您提供一个基本的通讯录管理系统的代码,如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 50
#define MAX_PHONE_LEN 20
#define MAX_EMAIL_LEN 50
#define MAX_CONTACTS 100
typedef struct {
char name[MAX_NAME_LEN];
char phone[MAX_PHONE_LEN];
char email[MAX_EMAIL_LEN];
} Contact;
Contact contacts[MAX_CONTACTS];
int num_contacts = 0;
void add_contact() {
if (num_contacts >= MAX_CONTACTS) {
printf("Error: Maximum number of contacts reached.\n");
return;
}
Contact new_contact;
printf("Enter name: ");
fgets(new_contact.name, MAX_NAME_LEN, stdin);
new_contact.name[strcspn(new_contact.name, "\n")] = '\0';
printf("Enter phone number: ");
fgets(new_contact.phone, MAX_PHONE_LEN, stdin);
new_contact.phone[strcspn(new_contact.phone, "\n")] = '\0';
printf("Enter email address: ");
fgets(new_contact.email, MAX_EMAIL_LEN, stdin);
new_contact.email[strcspn(new_contact.email, "\n")] = '\0';
contacts[num_contacts++] = new_contact;
printf("Contact added successfully.\n");
}
void list_contacts() {
if (num_contacts == 0) {
printf("No contacts found.\n");
return;
}
printf("Contacts:\n");
for (int i = 0; i < num_contacts; i++) {
printf("%d. Name: %s\n Phone: %s\n Email: %s\n", i+1, contacts[i].name, contacts[i].phone, contacts[i].email);
}
}
void search_contacts() {
if (num_contacts == 0) {
printf("No contacts found.\n");
return;
}
char search_term[MAX_NAME_LEN];
printf("Enter search term: ");
fgets(search_term, MAX_NAME_LEN, stdin);
search_term[strcspn(search_term, "\n")] = '\0';
int num_results = 0;
for (int i = 0; i < num_contacts; i++) {
if (strstr(contacts[i].name, search_term) != NULL) {
printf("%d. Name: %s\n Phone: %s\n Email: %s\n", i+1, contacts[i].name, contacts[i].phone, contacts[i].email);
num_results++;
}
}
if (num_results == 0) {
printf("No results found.\n");
}
}
int main() {
int choice;
while (1) {
printf("\n");
printf("1. Add contact\n");
printf("2. List contacts\n");
printf("3. Search contacts\n");
printf("4. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
getchar();
switch (choice) {
case 1:
add_contact();
break;
case 2:
list_contacts();
break;
case 3:
search_contacts();
break;
case 4:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice.\n");
}
}
return 0;
}
阅读全文