用C++写一个小型通讯录管理系统
时间: 2024-06-14 13:03:57 浏览: 113
以下是一个用C++写的小型通讯录管理系统的示例:
```cpp
#include <iostream>
#include <string>
using namespace std;
#define MAX 1000
// 联系人结构体
struct Person {
string m_Name; // 姓名
int m_Sex; // 性别:1男2女
int m_Age; // 年龄
string m_Phone; // 电话
string m_Addr; // 地址
};
// 通讯录结构体
struct Addressbooks {
Person personArray[MAX]; // 通讯录中保存的联系人数组
int m_Size; // 通讯录中当前记录的联系人数量
};
// 添加联系人
void addPerson(Addressbooks& abs) {
if (abs.m_Size == MAX) {
cout << "通讯录已满,无法添加!" << endl;
return;
}
string name;
cout << "请输入姓名:";
cin >> name;
abs.personArray[abs.m_Size].m_Name = name;
int sex;
cout << "请输入性别:1男 2女:";
while (true) {
cin >> sex;
if (sex == 1 || sex == 2) {
abs.personArray[abs.m_Size].m_Sex = sex;
break;
} else {
cout << "输入有误,请重新输入:";
}
}
int age;
cout << "请输入年龄:";
cin >> age;
abs.personArray[abs.m_Size].m_Age = age;
string phone;
cout << "请输入电话:";
cin >> phone;
abs.personArray[abs.m_Size].m_Phone = phone;
string addr;
cout << "请输入地址:";
cin >> addr;
abs.personArray[abs.m_Size].m_Addr = addr;
abs.m_Size++;
cout << "联系人添加成功!" << endl;
}
// 显示所有联系人
void showPerson(Addressbooks& abs) {
if (abs.m_Size == 0) {
cout << "通讯录为空!" << endl;
return;
}
for (int i = 0; i < abs.m_Size; i++) {
cout << "姓名:" << abs.personArray[i].m_Name << "\t";
cout << "性别:" << (abs.personArray[i].m_Sex == 1 ? "男" : "女") << "\t";
cout << "年龄:" << abs.personArray[i].m_Age << "\t";
cout << "电话:" << abs.personArray[i].m_Phone << "\t";
cout << "地址:" << abs.personArray[i].m_Addr << endl;
}
}
int main() {
Addressbooks abs;
abs.m_Size = 0;
while (true) {
cout << "***************************" << endl;
cout << "***** 1.添加联系人 *******" << endl;
cout << "***** 2.显示联系人 *******" << endl;
cout << "***** 3.退出通讯录 *******" << endl;
cout << "***************************" << endl;
int select;
cout << "请选择操作:";
cin >> select;
switch (select) {
case 1: // 添加联系人
addPerson(abs);
break;
case 2: // 显示联系人
showPerson(abs);
break;
case 3: // 退出通讯录
cout << "欢迎下次使用!" << endl;
return 0;
default:
cout << "输入有误,请重新选择!" << endl;
break;
}
}
return 0;
}
```
阅读全文