C++ function cout redirect to file -
say have simple function named print
, loop uses cout
print, say, 1-5, console.
is there way can like:
file << print ();
to output of print
saved file? assuming open file ofstream
properly, , everything.
assuming print
void
function output hard-coded cout
, there nothing can do: output controlled execution environment's assignment of output stream (console default or file redirect >myoutput.txt
).
if program control output goes, pass ostream&
print
function, , use output:
void print(ostream& ostr) { // use ostr instead of cout ostr << "hello, world!" << endl; }
if want print
output console or default output, call
print(cout);
if want write file, make ofstream
, , pass print
:
ofstream file("hello.txt"); print(file);