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::cout
is anstd::ostream
, so you must use the least common denominator.This took about two hours to get. Basically, I have a external class running a test suite. I send in a delegate to run the tests, so in order to have access to output I need to send in an output stream. I guess I could have done a different stream per test. Anyways, I wanted to pass in the ofstream to be used later.
I think Adam's on the right track but I don't think you can assign references - you need to use a pointer instead:
you could then define a reference to be the value of the pointer, but it wouldn't be global
You can find a very detailed explanation of how to do this here: http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81?pli=1
Hopefully someone will write this up more clearly for stack overflow to take the points...
I assume your program behaves like standard unix tools, that when not given a file will write to standard output, and when given a file will write into that file. You can redirect
cout
to write into another stream buffer. As long as your redirection is alive, everything written to cout is transparently written to the destination you designated. Once the redirection object goes out of scope, the original stream is put and output will write to the screen again:Now, cout is redirected to the file as long as the pipe is alive in main. You can make it more "production ready" by making it non-copyable, because it's not ready to be copied: If the copy goes out of scope, it would restore the original stream already.
Following Adam Rosenfield's tracks, but fixing the reference initialization problem with ternary and comma operators:
(Tested in VS)