In ANSI C++, how can I assign the cout stream to a variable name? What I want to do is, if the user has specified an output file name, I send output there, otherwise, send it to the screen. So something like:
ofstream outFile; if (outFileRequested) outFile.open('foo.txt', ios::out); else outFile = cout; // Will not compile because outFile does not have an // assignment operator outFile << 'whatever' << endl;
I tried doing this as a Macro function as well:
#define OUTPUT outFileRequested?outFile:cout OUTPUT << 'whatever' << endl;
But that gave me a compiler error as well.
I supposed I could either use an IF-THEN block for every output, but I’d like to avoid that if I could. Any ideas?
Use a reference. Note that the reference must be of type
std::ostream, notstd::ofstream, sincestd::coutis anstd::ostream, so you must use the least common denominator.