/* The original version of this program can be found at http://damb.dk */
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <string>

class CDRecordClass
{
public:
   std::string Title;
   std::string Artist;
};

std::istream & operator >> (std::istream &is, CDRecordClass &CDRecord)
{
   std::getline(is, CDRecord.Title);
   std::getline(is, CDRecord.Artist);
   return is;
}

std::ostream &operator << (std::ostream &os, const CDRecordClass &CDRecord)
{
   os << CDRecord.Title << std::endl;
   os << CDRecord.Artist;
   return os;
}

int main()
{
   std::vector<CDRecordClass >MyVector; // Our database
   std::ifstream is("test.dat");        // Try to open the file
   if(is)
   {  // The file could be opened, so read it
      std::copy(std::istream_iterator<CDRecordClass>(is),
                std::istream_iterator<CDRecordClass>(),
                std::back_inserter(MyVector));
      is.close();
   }
   // Write what we have juste read, to screen
   std::copy(MyVector.begin(),
             MyVector.end(),
             std::ostream_iterator<CDRecordClass>(std::cout, "n"));

   // Ask the user for another album
   CDRecordClass CDRecord;
   std::cout << "Enter title: ";
   std::getline(std::cin, CDRecord.Title);
   std::cout << "Enter artist: ";
   std::getline(std::cin, CDRecord.Artist);

   // Write the album just entered:
   std::cout << CDRecord << std::endl;

   // And add it to the vector
   MyVector.push_back(CDRecord);

   // Write everything into the file
   std::ofstream os("test.dat");
   if(os)
   {
      std::copy(MyVector.begin(),
                MyVector.end(),
                std::ostream_iterator<CDRecordClass>(os, "n"));
   }
   else
   {
      std::cout << "Failed to open file for writing" << std::endl;
   }
}