用c语言写一个电子通讯录
时间: 2024-05-28 07:09:07 浏览: 19
好的,以下是一个简单的电子通讯录的 C 语言代码示例:
#include <stdio.h>
#include <string.h>
#define MAX_CONTACTS 100
struct Contact {
char name[50];
char phone[20];
char email[50];
};
int numContacts = 0;
struct Contact contacts[MAX_CONTACTS];
void addContact() {
if (numContacts >= MAX_CONTACTS) {
printf("Error: Maximum number of contacts reached.\n");
return;
}
struct Contact newContact;
printf("Enter name: ");
fgets(newContact.name, 50, stdin);
newContact.name[strcspn(newContact.name, "\n")] = 0; // remove trailing newline
printf("Enter phone number: ");
fgets(newContact.phone, 20, stdin);
newContact.phone[strcspn(newContact.phone, "\n")] = 0;
printf("Enter email address: ");
fgets(newContact.email, 50, stdin);
newContact.email[strcspn(newContact.email, "\n")] = 0;
contacts[numContacts] = newContact;
numContacts++;
printf("Contact added successfully.\n");
}
void listContacts() {
if (numContacts == 0) {
printf("No contacts found.\n");
return;
}
printf("Contacts:\n");
for (int i = 0; i < numContacts; i++) {
printf("%d. Name: %s, Phone: %s, Email: %s\n", i+1, contacts[i].name, contacts[i].phone, contacts[i].email);
}
}
int main() {
int choice;
do {
printf("\n1. Add contact\n2. List contacts\n3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // consume newline left by scanf
switch (choice) {
case 1:
addContact();
break;
case 2:
listContacts();
break;
case 3:
printf("Goodbye!\n");
break;
default:
printf("Invalid choice.\n");
}
} while (choice != 3);
return 0;
}
当然,这只是一个简单的示例,你可以根据需求进行修改和扩展。