用C++编写一个通讯录的代码
#include <stdio.h>
#include <string.h>
#define MAX_CONTACTS 100
struct Contact {
char name[30];
char phoneNumber[15];
};
void addContact(struct Contact contacts[], int *numContacts);
void displayContacts(struct Contact contacts[], int numContacts);
int main() {
struct Contact contacts[MAX_CONTACTS];
int numContacts = 0;
char choice;
do {
printf("Menu:
");
printf("1. Add Contact
");
printf("2. Display Contacts
");
printf("3. Exit
");
printf("Enter your choice: ");
scanf(" %c", &choice);
switch (choice) {
case '1':
addContact(contacts, &numContacts);
break;
case '2':
displayContacts(contacts, numContacts);
break;
case '3':
printf("Exiting...
");
break;
default:
printf("Invalid choice. Please try again.
");
}
} while (choice != '3');
return 0;
}
void addContact(struct Contact contacts[], int *numContacts) {
if (*numContacts == MAX_CONTACTS) {
printf("Unable to add contact. Contact list is full.
");
return;
}
struct Contact newContact;
printf("Enter name: ");
scanf("%s", newContact.name);
printf("Enter phone number: ");
scanf("%s", newContact.phoneNumber);
contacts[*numContacts] = newContact;
(*numContacts)++;
printf("Contact added successfully.
");
}
void displayContacts(struct Contact contacts[], int numContacts) {
if (numContacts == 0) {
printf("No contacts found.
");
return;
}
printf("Contact List:
");
for (int i = 0; i < numContacts; i++) {
printf("Name: %s
", contacts[i].name);
printf("Phone number: %s
", contacts[i].phoneNumber);
printf("----------------------
");
}
}
智能问答AI写作网
免责声明:
本内容由智能问答AI写作网生成,请根据需求酌情使用,点击这里>>使用AI创作问答升级版,更聪明、更完整、更原创!
以上内容除特别注明外均来源于网友提问,智能问答AI写作网回答,权益归原著者所有;