Search code examples
c++fstreamcoutio-redirectionofstream

ofstream - Can I redirect a "cout" into file?


I just wanted to know if there was some way yo be able to do this :

ofstream exemple (name);
exemple << Display();

Display() being a void method, that only do something like that :

cout << "Something" << endl;

I would do that because I have already written all the methods Display() for each class and I would like to put what they send to cout into my file, instead or recreate some methods "string Display()".

Is it possible?

Thank's! Marco


Solution

  • You can change cout's buffer, but cout is a global variable so that will affect the whole program.

    Why don't you make Display() receive the output stream as parameter?

    void Display(std::ostream &cout) {
        cout << "Something" << endl;
    }