用c++语言按以下要求编写程序: 形成一个通讯录存储在文本文件里,此通讯录有查找输入,输出,删除功能,姓名和号码都支持不完全输入查找,输出运行结果。通讯录有姓名、电话号码,当输人电话号码时,查找出姓名 与电话号码;当输入姓名时,同样查找出姓名与电话号码;还允许不完全输入查找,例如输入 010时查找出所有以010开头的号码,输入“杨”时列出所有姓名以“杨”开头的号码
时间: 2024-03-11 15:47:32 浏览: 21
很好,以下是一个简单的实现:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Contact {
string name;
string phone;
};
void addContact(vector<Contact>& contacts) {
Contact newContact;
cout << "请输入姓名:";
cin >> newContact.name;
cout << "请输入电话号码:";
cin >> newContact.phone;
contacts.push_back(newContact);
cout << "添加成功!" << endl;
}
void searchContact(const vector<Contact>& contacts, const string& keyword) {
bool found = false;
for (const auto& contact : contacts) {
if (contact.name.find(keyword) != string::npos ||
contact.phone.find(keyword) != string::npos) {
cout << contact.name << " " << contact.phone << endl;
found = true;
}
}
if (!found) {
cout << "未找到匹配的记录!" << endl;
}
}
void deleteContact(vector<Contact>& contacts, const string& keyword) {
auto it = remove_if(contacts.begin(), contacts.end(), [&](const Contact& contact) {
return contact.name.find(keyword) != string::npos ||
contact.phone.find(keyword) != string::npos;
});
int count = distance(it, contacts.end());
contacts.erase(it, contacts.end());
cout << "删除成功,共删除 " << count << " 条记录!" << endl;
}
void showContacts(const vector<Contact>& contacts) {
cout << "通讯录:" << endl;
for (const auto& contact : contacts) {
cout << contact.name << " " << contact.phone << endl;
}
}
int main() {
vector<Contact> contacts;
string filename = "contacts.txt";
ifstream fin(filename);
if (fin.is_open()) {
string line;
while (getline(fin, line)) {
Contact contact;
size_t pos = line.find(' ');
contact.name = line.substr(0, pos);
contact.phone = line.substr(pos + 1);
contacts.push_back(contact);
}
fin.close();
cout << "已从文件 " << filename << " 中读取 " << contacts.size() << " 条记录!" << endl;
}
while (true) {
cout << "请输入操作:1-新增,2-查找,3-删除,4-显示所有记录,0-退出:";
int cmd;
cin >> cmd;
if (cmd == 1) {
addContact(contacts);
ofstream fout(filename, ios::app);
fout << contacts.back().name << " " << contacts.back().phone << endl;
fout.close();
} else if (cmd == 2) {
string keyword;
cout << "请输入关键字:";
cin >> keyword;
searchContact(contacts, keyword);
} else if (cmd == 3) {
string keyword;
cout << "请输入关键字:";
cin >> keyword;
deleteContact(contacts, keyword);
ofstream fout(filename);
for (const auto& contact : contacts) {
fout << contact.name << " " << contact.phone << endl;
}
fout.close();
} else if (cmd == 4) {
showContacts(contacts);
} else if (cmd == 0) {
break;
} else {
cout << "无效的操作!" << endl;
}
}
return 0;
}
```
这个程序使用了一个 `Contact` 结构体来表示单个通讯录条目,其中包含姓名和电话号码两个字段。通讯录数据存储在一个 `vector<Contact>` 中,并且可以通过文件读写来实现数据的持久化。程序提供了四个操作:新增、查找、删除和显示所有记录。其中,查找和删除操作都支持不完全输入的关键字匹配。