#include "repo.h" #include #include Repository::Repository() { this->read_from_file(); } Repository::~Repository() { this->write_to_file(); } std::vector Repository::users() { return this->_users; } std::vector Repository::items() { return this->_items; } void Repository::add_item(Item item) { for(auto it : this->_items){ if(it.name() == item.name()){ throw std::runtime_error("Item already exists"); } } this->_items.push_back(item); } Item& Repository::find_item(std::string name) { for(auto& it : this->_items){ if(it.name() == name){ return it; } } throw std::runtime_error("Item not found"); } void Repository::read_from_file() { std::ifstream f("items.txt"); std::string name, category; int price; std::string line; std::string buf; int user_id; std::string date; int offer_price; while(std::getline(f,line) || line != ""){ buf=line.substr(0, line.find("|")); name = buf; line.erase(0, line.find("|")+1); buf=line.substr(0, line.find("|")); category = buf; line.erase(0, line.find("|")+1); buf=line.substr(0, line.find("|")); price = std::stoi(buf); line.erase(0, line.find("|")+1); std::vector> offers; while(line != ""){ buf=line.substr(0, line.find(",")); user_id = std::stoi(buf); line.erase(0, line.find(",")+1); buf=line.substr(0, line.find(",")); date = buf; line.erase(0, line.find(",")+1); buf=line.substr(0, line.find(",")); offer_price = std::stoi(buf); line.erase(0, line.find(";")+1); offers.push_back(std::make_tuple(user_id, date, offer_price)); } this->_items.push_back(Item(name, category, price, offers)); } std::string type; int id; std::ifstream g("users.txt"); while(std::getline(g,line) || line != ""){ buf=line.substr(0, line.find("|")); id = std::stoi(buf); line.erase(0, line.find("|")+1); buf=line.substr(0, line.find("|")); name = buf; line.erase(0, line.find("|")+1); buf=line.substr(0, line.find("|")); type = buf; line.erase(0, line.find("|")+1); this->_users.push_back(User(name, id, type)); } f.close(); g.close(); } void Repository::write_to_file() { std::ofstream f("items.txt"); for(auto it : this->_items){ f<(it2)<<","<(it2)<<","<(it2)<<";"; } f<<"\n"; } f.close(); }