用c++语言设计和实现一个“通信录管理系统”,实现对通信录进行管理
时间: 2024-02-11 07:09:35 浏览: 26
好的,我会尽力回答您的问题。
通信录管理系统是一个常见的管理软件,用于管理联系人信息。下面是一个简单的C++程序,实现了基本的通信录管理功能:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Contact {
string name;
string phone;
};
class AddressBook {
public:
void addContact(Contact contact) {
contacts.push_back(contact);
cout << "Added contact: " << contact.name << endl;
}
void removeContact(int index) {
if (index < 0 || index >= contacts.size()) {
cout << "Invalid index: " << index << endl;
return;
}
Contact contact = contacts[index];
contacts.erase(contacts.begin() + index);
cout << "Removed contact: " << contact.name << endl;
}
void listContacts() {
cout << "Contacts:" << endl;
for (int i = 0; i < contacts.size(); i++) {
Contact contact = contacts[i];
cout << i << ". " << contact.name << " (" << contact.phone << ")" << endl;
}
}
private:
vector<Contact> contacts;
};
int main() {
AddressBook addressBook;
while (true) {
cout << "1. Add contact" << endl;
cout << "2. Remove contact" << endl;
cout << "3. List contacts" << endl;
cout << "4. Exit" << endl;
int choice;
cin >> choice;
if (choice == 1) {
cout << "Name: ";
string name;
cin >> name;
cout << "Phone: ";
string phone;
cin >> phone;
Contact contact = { name, phone };
addressBook.addContact(contact);
}
else if (choice == 2) {
cout << "Index: ";
int index;
cin >> index;
addressBook.removeContact(index);
}
else if (choice == 3) {
addressBook.listContacts();
}
else if (choice == 4) {
break;
}
else {
cout << "Invalid choice: " << choice << endl;
}
}
return 0;
}
```
这个程序定义了一个`Contact`结构体,包含一个人的姓名和电话号码。`AddressBook`类维护一个`vector`,存储所有联系人。该类提供了三个方法:添加联系人、删除联系人和列出所有联系人。在`main`函数中,使用一个无限循环来接收用户的输入,根据用户选择的选项来调用相应的方法。
希望这个程序能够对您有所帮助!