Hello, this is my first post here.
I am a novice C++ programmer, and I've come upon a problem that I don't know how to solve. What I'm trying to do is send some output first to cout and then to a file. The obvious way to do this would be something like:
However, if "Some text" is a whole bunch of output then this is a lot of code duplication. What I'd like to do is define an array of streams that has 2 elements. The first is cout and the second is my file stream. Then I'd have a loop over this stream array, and write the same stuff to each stream.Code:#include "iostream" #include "fstream" ... ofstream Log("./Log"); cout << "Some text." << endl; Log << "Some text." << endl; Log.close(); ...
But I can't quite get it to work. The best I've been able to come up with (after some scanning of the internet) is this:
This almost works. It sends everything to cout just as it should, but it chokes at the first "endl" when sending to my file, so that the file simply contains "Some text.".Code:#include "iostream" #include "fstream" ... ofstream Log("./Log"); ostream s[2]; s[0].rdbuf(cout.rdbuf()); s[1].rdbuf(Log.rdbuf()); int i; for(i=0; i<2; i++){ s[i] << "Some text." << endl; s[i] << "Some more text." << endl; } ...
What am I doing wrong, and is there a more elegant way of accomplishing this?
Thanks very much for any and all help.



LinkBack URL
About LinkBacks



