fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <vector>
  5. #include <boost/lexical_cast.hpp>
  6. using namespace std;
  7.  
  8. struct Journal
  9. {
  10. string title;
  11. vector<string> entries;
  12.  
  13. explicit Journal(const string& title)
  14. : title{title}
  15. {
  16. }
  17.  
  18. void add(const string& entry);
  19.  
  20. // persistence is a separate concern
  21. void save(const string& filename);
  22. };
  23.  
  24. void Journal::add(const string& entry)
  25. {
  26. static int count = 1;
  27. entries.push_back(boost::lexical_cast<string>(count++)
  28. + ": " + entry);
  29. }
  30.  
  31. void Journal::save(const string& filename)
  32. {
  33. ofstream ofs(filename);
  34. for (auto& s : entries)
  35. ofs << s << endl;
  36. }
  37.  
  38. struct PersistenceManager
  39. {
  40. static void save(const Journal& j, const string& filename)
  41. {
  42. ofstream ofs(filename);
  43. for (auto& s : j.entries)
  44. {
  45. ofs << s << endl;
  46. std::cout << s << endl;
  47. }
  48. }
  49. };
  50.  
  51. int main()
  52. {
  53. Journal journal{"Dear Diary"};
  54. journal.add("I ate a bug");
  55. journal.add("I cried today");
  56.  
  57. //journal.save("diary.txt");
  58.  
  59. PersistenceManager pm;
  60. pm.save(journal, "diary.txt");
  61.  
  62. return 0;
  63. }
Success #stdin #stdout 0.01s 5516KB
stdin
Standard input is empty
stdout
1: I ate a bug
2: I cried today