用c++写一个建议通讯录
时间: 2024-02-18 17:45:44 浏览: 68
C++写的通讯录
#include<stdio.h>
#include<string.h>
#define MAX 100
struct Person {
char name[20];
char tel[20];
};
struct Person person[MAX];
int cnt = 0;
void addPerson() {
if (cnt == MAX) {
printf("通讯录已满,无法添加!\n");
return;
}
printf("请输入联系人姓名和电话号码,用空格隔开:");
scanf("%s %s", person[cnt].name, person[cnt].tel);
cnt++;
printf("添加成功!\n");
}
void showList() {
if (cnt == 0) {
printf("通讯录为空,无法显示!\n");
return;
}
printf("姓名\t电话号码\n");
for (int i = 0; i < cnt; i++) {
printf("%s\t%s\n", person[i].name, person[i].tel);
}
}
void searchPerson() {
if (cnt == 0) {
printf("通讯录为空,无法查询!\n");
return;
}
char name[20];
printf("请输入要查找的联系人姓名:");
scanf("%s", name);
int flag = 0;
for (int i = 0; i < cnt; i++) {
if (strcmp(name, person[i].name) == 0) {
printf("%s的电话号码是%s\n", name, person[i].tel);
flag = 1;
break;
}
}
if (flag == 0) {
printf("未找到该联系人!\n");
}
}
void deletePerson() {
if (cnt == 0) {
printf("通讯录为空,无法删除!\n");
return;
}
char name[20];
printf("请输入要删除的联系人姓名:");
scanf("%s", name);
int flag = 0;
for (int i = 0; i < cnt; i++) {
if (strcmp(name, person[i].name) == 0) {
for (int j = i; j < cnt - 1; j++) {
strcpy(person[j].name, person[j + 1].name);
strcpy(person[j].tel, person[j + 1].tel);
}
cnt--;
printf("删除成功!\n");
flag = 1;
break;
}
}
if (flag == 0) {
printf("未找到该联系人!\n");
}
}
int main() {
int choice = 0;
while (1) {
printf("请选择要进行的操作:\n");
printf("1.添加联系人\n");
printf("2.显示联系人列表\n");
printf("3.查找联系人\n");
printf("4.删除联系人\n");
printf("5.退出程序\n");
scanf("%d", &choice);
switch (choice) {
case 1:
addPerson();
break;
case 2:
showList();
break;
case 3:
searchPerson();
break;
case 4:
deletePerson();
break;
case 5:
printf("程序已退出!\n");
return 0;
default:
printf("输入有误,请重新输入!\n");
break;
}
}
}
阅读全文