From 2557943ae3a08088102e29463a1c0bc5d360668d Mon Sep 17 00:00:00 2001 From: paxmbrt4l Date: Sat, 22 Jun 2024 15:40:56 +0800 Subject: [PATCH] Add ContactManager.cpp --- ContactManager.cpp | 54 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 ContactManager.cpp diff --git a/ContactManager.cpp b/ContactManager.cpp new file mode 100644 index 0000000..0977e25 --- /dev/null +++ b/ContactManager.cpp @@ -0,0 +1,54 @@ +#include "ContactManager.h" +#include "Contact.h" + +ContactManager::ContactManager() {} + +void ContactManager::addContact(const std::string& name, const std::string& phone, const std::string& email) { + contacts.push_back(Contact(name, phone, email)); +} + +void ContactManager::removeContact(const std::string& name) { + contacts.erase(std::remove_if(contacts.begin(), contacts.end(), [&name](const Contact& contact) { + return contact.name == name; + }), contacts.end()); +} + +void ContactManager::displayContacts() { + for (const auto& contact : contacts) { + std::cout << contact.name << ", " << contact.phone << ", " << contact.email << std::endl; + } +} + +void ContactManager::saveToFile(const std::string& filename) { + std::ofstream file(filename); + if (file.is_open()) { + for (const auto& contact : contacts) { + file << contact.name << ", " << contact.phone << ", " << contact.email << std::endl; + } + file.close(); + } else { + std::cerr << "Unable to open file." << std::endl; + } +} + +void ContactManager::loadFromFile(const std::string& filename) { + contacts.clear(); + std::ifstream file(filename); + if (file.is_open()) { + std::string line; + while (std::getline(file, line)) { + size_t pos = line.find(", "); + std::string name = line.substr(0, pos); + line.erase(0, pos + 2); + + pos = line.find(", "); + std::string phone = line.substr(0, pos); + std::string email = line.substr(pos + 2); + + addContact(name, phone, email); + } + file.close(); + } else { + std::cerr << "Unable to open file." << std::endl; + } +}