//=============================================================================

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

//-----------------------------------------------------------------------------

using collection = vector<string>;

const string filename("strings.txt");

//-------------------------------------------------------------------------------

void insert(collection& c)
{
   cout << "\nString eingeben: ";
   string s;
   getline(cin, s);
   c.push_back(s);
}

//-------------------------------------------------------------------------------

void list(const collection& c)
{
   cout << '\n' << c.size() << " Strings:\n";
   for (const string& s : c)
   {
      cout << "- \"" << s << '"' << '\n';
   }
}

//-------------------------------------------------------------------------------

void save(const collection& c)
{
   cout << "\nSpeichern in Datei \"" << filename << "\"\n";

   ofstream out(filename);
   if (out.fail())
   {
      cout << "- Probleme beim Oeffnen der Datei.\n";
      return;
   }

   for (const string& s : c)
   {
      out << s << '\n';
      if (out.fail())
      {
         cout << "- Probleme beim Schreiben in die Datei.\n";
         return;
      }
   }

   cout << "- fertig\n";
}

//-------------------------------------------------------------------------------

void load(collection& c)
{
   cout << "\nLaden aus Datei \"" << filename << "\"\n";

   ifstream in(filename);
   if (in.fail())
   {
      cout << "- Probleme beim Oeffnen der Datei.\n";
      return;
   }

   c.clear();
   for (string s;;)
   {
      getline(in, s);
      if (in.fail()) break;
      c.push_back(s);
   }
   if (!in.eof())
   {
      cout << "- Probleme beim Lesen aus der Datei.\n";
   }

   cout << "- " << c.size() << " Strings geladen\n";
}

//-------------------------------------------------------------------------------

int main()
{
   cout << "Aufg_13_02_String_Container\n\n";

   collection c;
   for (string s;;)
   {
      cout << "\nVektor fuer Strings\n"
         "i - Eingabe eines neues Strings\n"
         "a - Ausgabe aller Strings\n"
         "s - Abspeichern der Eintraege in die Datei\n"
         "l - Laden der Datei\n"
         "e - Programmende\n"
         "> ";
      getline(cin, s);
      if (s.empty()) continue;
      switch (s[0])
      {
      case 'i':
         insert(c);
         break;
      case 'a':
         list(c);
         break;
      case 's':
         save(c);
         break;
      case 'l':
         load(c);
         break;
      case 'e':
         return 0;
      }
   }
}
