You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
LXW/通讯录管理系统

140 lines
4.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <iostream>
#include <vector>
#include <string>
// 定义联系人结构体
class Contact {
public:
int id;
std::string name;
std::string phone;
};
// 定义联系人管理类
class ContactManager {
private:
std::vector<Contact> contacts; // 存储联系人的向量
public:
// 添加联系人
void addContact() {
Contact newContact;
std::cout << "请输入联系人姓名: ";
std::cin >> newContact.name;
std::cout << "请输入联系人电话: ";
std::cin >> newContact.phone;
newContact.id = contacts.size() + 1;
contacts.push_back(newContact);
}
// 更新联系人
void updateContact() {
int id;
std::cout << "请输入要更新的联系人ID ";
std::cin >> id;
for (auto& contact : contacts) {
if (contact.id == id) {
std::cout << "找到联系人,请输入新的姓名: ";
std::cin >> contact.name;
std::cout << "请输入新的电话: ";
std::cin >> contact.phone;
std::cout << "联系人已更新。" << std::endl;
return;
}
}
std::cout << "未找到联系人。" << std::endl;
}
// 显示通讯录
void displayContacts() const {
std::cout << "通讯录如下:" << std::endl;
for (const auto& contact : contacts) {
std::cout << "ID " << contact.id << ", 姓名: " << contact.name << ", 电话: " << contact.phone << std::endl;
}
}
// 查找联系人
void findContact() const {
int id;
std::cout << "请输入要查找的联系人ID ";
std::cin >> id;
for (const auto& contact : contacts) {
if (contact.id == id) {
std::cout << "找到联系人ID " << contact.id << ", 姓名: " << contact.name << ", 电话: " << contact.phone << std::endl;
return;
}
}
std::cout << "未找到联系人。" << std::endl;
}
// 删除联系人
void deleteContact() {
int id;
std::cout << "请输入要删除的联系人ID ";
std::cin >> id;
for (auto it = contacts.begin(); it != contacts.end(); ++it) {
if (it->id == id) {
contacts.erase(it);
std::cout << "已删除联系人。" << std::endl;
return;
}
}
std::cout << "未找到联系人。" << std::endl;
}
// 清空通讯录
void clearContacts() {
contacts.clear();
std::cout << "已清空通讯录。" << std::endl;
}
};
int main() {
ContactManager manager; // 创建联系人管理对象
int choice;
while (true) {
std::cout << "1. 添加联系人" << std::endl;
std::cout << "2. 更新联系人" << std::endl;
std::cout << "3. 显示通讯录" << std::endl;
std::cout << "4. 查找联系人" << std::endl;
std::cout << "5. 删除联系人" << std::endl;
std::cout << "6. 清空通讯录" << std::endl;
std::cout << "0. 退出程序" << std::endl;
std::cout << "请输入您的选择: ";
std::cin >> choice;
switch (choice) {
case 1:
manager.addContact(); // 调用添加联系人方法
break;
case 2:
manager.updateContact(); // 调用更新联系人方法
break;
case 3:
manager.displayContacts(); // 调用显示通讯录方法
break;
case 4:
manager.findContact(); // 调用查找联系人方法
break;
case 5:
manager.deleteContact(); // 调用删除联系人方法
break;
case 6:
manager.clearContacts(); // 调用清空通讯录方法
break;
case 0:
return 0; // 退出程序
default:
std::cout << "无效的选择,请重新输入。" << std::endl;
}
}
return 0;
}