c++filehttp-redirectcout

C++ function cout redirect to file


Say I have a simple function named print, with a loop that uses cout to print, say, 1-5, to the console.

Is there a way I can do something like:

file << print ();

To get the output of print saved into a file? Obviously assuming I open the file with ofstream properly, and everything.


Solution

  • Assuming that print is a void function with its output hard-coded to cout, there is nothing you can do: the output will be controlled by the execution environment's assignment of the output stream (console by default or a file redirect with >myoutput.txt).

    If you would like your program to control where the output goes, pass ostream& to your print function, and use it for the output:

    void print(ostream& ostr) {
        // use ostr instead of cout
        ostr << "hello, world!" << endl;
    }
    

    If you want print to output to console or the default output, call

    print(cout);
    

    If you want it to write to a file, make an ofstream, and pass it to print:

    ofstream file("hello.txt");
    print(file);