C++通讯录
时间: 2023-07-11 22:06:44 浏览: 53
以下是一个简单的 C++ 通讯录程序,可以通过命令行进行交互:
```cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Contact {
string name;
string phone;
};
vector<Contact> contacts;
void add_contact() {
Contact c;
cout << "Enter name: ";
getline(cin, c.name);
cout << "Enter phone number: ";
getline(cin, c.phone);
contacts.push_back(c);
}
void list_contacts() {
if (contacts.empty()) {
cout << "No contacts found." << endl;
return;
}
cout << "Contacts:" << endl;
for (const auto& c : contacts) {
cout << c.name << " - " << c.phone << endl;
}
}
int main() {
while (true) {
string command;
cout << "Enter command (add, list, quit): ";
getline(cin, command);
if (command == "add") {
add_contact();
} else if (command == "list") {
list_contacts();
} else if (command == "quit") {
break;
} else {
cout << "Invalid command" << endl;
}
}
return 0;
}
```
这个程序定义了一个 `Contact` 结构体,包含姓名和电话号码。使用 `vector` 存储所有的联系人。程序提供了三个命令:`add` 添加联系人,`list` 列出所有联系人,`quit` 退出程序。