// MT1Q2.cpp - Message Logger #include #include #include #include #include #include #include #include "../Utilities/Utilities.h" std::string getTimeDate() { //http://stackoverflow.com/questions/997946/how-to-get-current-time-and-date-in-c time_t now = time(0); struct tm tstruct; char buf[80]; errno_t err = localtime_s(&tstruct, &now); // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime // for more information about date/time format strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct); return buf; } struct ILog { using Msg = std::pair < std::string, std::string > ; using iterator = std::vector::iterator; virtual ~ILog() {} virtual void message(const std::string& time, const std::string& text)=0; virtual iterator begin()=0; virtual iterator end()=0; virtual void show()=0; virtual bool save()=0; }; struct factory { ILog* create(); }; class Log : public ILog { public: using Msg = std::pair < std::string, std::string >; using iterator = std::vector::iterator; void message(const std::string& time, const std::string& text); virtual iterator begin() { return log_.begin(); } virtual iterator end() { return log_.end(); } void show(); bool save(); // compiler generated methods are correct private: using Msg = std::pair < std::string, std::string >; std::vector log_; // stores in arrival order }; // std::list may have better performance ILog* factory::create() { return new Log(); } void Log::message(const std::string& time, const std::string& text) { Msg msg; msg.first = time; msg.second = text; log_.push_back(msg); } void Log::show() { std::cout << "\n Message Log"; std::cout << "\n -------------"; for (auto msg : log_) { std::cout << "\n " << msg.first << " " << msg.second; } std::cout << "\n"; } bool Log::save() { std::ofstream out("logfile.txt", std::ios::app); if (out.good()) { for (auto msg : log_) { out << "\n " << msg.first << " " << msg.second; } out.close(); log_.clear(); return true; } return false; } int main() { title("MT1Q2 and MT1Q4 - Message Logger", '='); title("testing message logging"); Log log; log.message(getTimeDate(), "first message"); log.message(getTimeDate(), "second message"); log.message(getTimeDate(), "third message"); log.show(); log.save(); log.show(); title("testing interface"); factory fact; ILog* pLog = fact.create(); pLog->message(getTimeDate(), "fourth message"); pLog->message(getTimeDate(), "fifth message"); pLog->message(getTimeDate(), "sixth message"); pLog->show(); pLog->save(); title("testing iterators"); for (auto item : *pLog) { std::cout << "\n " << item.first << " " << item.second; } std::cout << "\n\n"; }