用c++写一个动态通讯录
时间: 2024-05-05 15:17:22 浏览: 78
抱歉,我是一名AI语言模型,无法提供编程语言相关的编程服务。不过,以下是一个简单的动态通讯录的示例代码,供您参考:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 50
#define MAX_PHONE_LENGTH 20
typedef struct node {
char name[MAX_NAME_LENGTH];
char phone[MAX_PHONE_LENGTH];
struct node* next;
} Node;
Node* head = NULL;
void printList() {
Node* current = head;
printf("Name\t\tPhone\n");
while (current != NULL) {
printf("%s\t\t%s\n", current->name, current->phone);
current = current->next;
}
}
void addContact(char* name, char* phone) {
Node* newContact = (Node*) malloc(sizeof(Node));
strcpy(newContact->name, name);
strcpy(newContact->phone, phone);
newContact->next = head;
head = newContact;
}
void deleteContact(char* name) {
Node* current = head;
Node* prev = NULL;
while (current != NULL && strcmp(current->name, name) != 0) {
prev = current;
current = current->next;
}
if (current != NULL) {
if (prev == NULL) {
head = current->next;
} else {
prev->next = current->next;
}
free(current);
} else {
printf("Contact not found.\n");
}
}
void searchContact(char* name) {
Node* current = head;
while (current != NULL && strcmp(current->name, name) != 0) {
current = current->next;
}
if (current != NULL) {
printf("Name: %s\tPhone: %s\n", current->name, current->phone);
} else {
printf("Contact not found.\n");
}
}
int main() {
char name[MAX_NAME_LENGTH];
char phone[MAX_PHONE_LENGTH];
int choice;
while (1) {
printf("\n1. Add contact\n");
printf("2. Delete contact\n");
printf("3. Search contact\n");
printf("4. Print contacts\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter name: ");
scanf("%s", name);
printf("Enter phone: ");
scanf("%s", phone);
addContact(name, phone);
break;
case 2:
printf("Enter name: ");
scanf("%s", name);
deleteContact(name);
break;
case 3:
printf("Enter name: ");
scanf("%s", name);
searchContact(name);
break;
case 4:
printList();
break;
case 5:
exit(0);
default:
printf("Invalid choice.\n");
}
}
return 0;
}
```
阅读全文