I was looking for a solution to write to a file and the console at the same time. I found a nice solution here.
As I am working pre C++11 I had to make a small change to the code from Lightness Races in Orbit:
#include <iostream>
#include <fstream>
#include <string>
struct OutputAndConsole : std::ofstream
{
OutputAndConsole(const std::string& fileName)
: std::ofstream(fileName.c_str()) // constructor taking a string is C++11
, fileName(fileName)
{};
const std::string fileName;
};
template <typename T>
OutputAndConsole& operator<<(OutputAndConsole& strm, const T& var)
{
std::cout << var;
static_cast<std::ofstream&>(strm) << var;
return strm;
};
It works nicely apart from a small thing takes puzzles me. If I use it like this:
int main(){
OutputAndConsole oac("testLog.dat");
double x = 5.0;
oac << std::endl;
static_cast<OutputAndConsole&>(oac << "foo \n" << x << "foo").operator<<(std::endl);
oac << "foo" << std::endl;
}
then all the std::endl
are ignored for the output on the console while they appear correctly in the file. My guess is that when I use std::endl
the ostream::operator<<
is called which will print to the file but not to the console. The line with the static_cast<OutputAndConsole&>
is my dilettantish attempt to call the correct operator, but still only the line break from \n
appears on the console.
Why for std::endl
the wrong operator is called?
How can I call the correct one?
PS: I know that I can use \n
without problems, but still I would like to know what is going on here and how to fix it.
'\n'
to end a line you won't have this problem. Do you really need the extra stuff thatstd::endl
does? – Wallyostream
already have operators which handle those. Let it do its job and handle formatted output. You just need to duplicate raw output over two other streams. It is a job forstreambuf
class. Just implement it properly and redirect all operatons to other two buffers: Dr.Dobb's article, another link – Pastoralofstream
. Maybe I should ask a new question about writing to console and file at the same time, if there is no dupe that I missed. – Opinionated