给我用c++写一个通讯录管理系统
时间: 2023-05-22 20:02:08 浏览: 56
好的,以下是一个简单的通讯录管理系统的 C 代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CONTACTS 100
struct Contact {
char name[50];
char phone[20];
};
struct Contact contacts[MAX_CONTACTS];
int num_contacts = 0;
void add_contact() {
if (num_contacts >= MAX_CONTACTS) {
printf("Error: too many contacts\n");
return;
}
struct Contact new_contact;
printf("Enter name: ");
fgets(new_contact.name, 50, stdin);
new_contact.name[strcspn(new_contact.name, "\n")] = '\0'; // remove newline
printf("Enter phone number: ");
fgets(new_contact.phone, 20, stdin);
new_contact.phone[strcspn(new_contact.phone, "\n")] = '\0'; // remove newline
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("%s: %s\n", contacts[i].name, contacts[i].phone);
}
}
int main() {
while (1) {
printf("Enter command (add, list, quit): ");
char command[10];
fgets(command, 10, stdin);
command[strcspn(command, "\n")] = '\0'; // remove newline
if (strcmp(command, "add") == 0) {
add_contact();
} else if (strcmp(command, "list") == 0) {
list_contacts();
} else if (strcmp(command, "quit") == 0) {
break;
} else {
printf("Invalid command\n");
}
}
return 0;
}