0

My code is supposed to read a file and from the information on that file create objects of class Movie and store them in a vector, How can I print those objects now that they are in the vector?

void Movie::loadFile(string file)
{
    ifstream inFile;

    inFile.open(file+".txt");
    try {
            if (!inFile)
                throw "UNABLE TO OPEN FILE";

            }catch (const char* msg)
            {
                cerr << msg << endl;
                exit(1);
            }

    while (inFile.good())
    {
        getline(inFile, id, ',');
        getline(inFile, name, ',');
        getline(inFile, tim, ',');
        getline(inFile, gen, ',');
        getline(inFile, rate, '\n');

        mov.push_back(new Movie(id, name, tim, gen, rate));
     }
    inFile.close();
    cout<<endl;
}

I have tried to do it by overloading an operator but I get the errors

error: 'std::vector<Movie*> Movie::mov' is protected within this context
error: 'ostream_iterator' was not declared in this scope
error: expected primary-expression before '>' token
ostream &operator <<(ostream& salida, const Movie& print)
{
    salida << print.id << endl;
    copy(print.mov.begin(), print.mov.end(), ostream_iterator<Video>(salida, " "));
    return salida;
}

I would really aprecciate the help :).

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52
  • `while (inFile.good())` is similar to this: [https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – drescherjm Jun 09 '20 at 21:53

1 Answers1

0

In order to use

copy(print.mov.begin(), print.mov.end(), ostream_iterator<Video>(salida, " "));

you need to implement the following overload.

std::ostream& operator<<(std::ostream&, Video const&);

From https://en.cppreference.com/w/cpp/iterator/ostream_iterator:

std::ostream_iterator is a single-pass LegacyOutputIterator that writes successive objects of type T into the std::basic_ostream object for which it was constructed, using operator<<.

R Sahu
  • 204,454
  • 14
  • 159
  • 270