Can I do : clog << cout << "test" << endl; ?

Hi all,

Can I do :

clog << cout << "Attempt to chain streams. This sentence should be printed twice" << endl;

Instead of :

1
2
clog << "Attempt to chain streams. This sentence should be printed twice" << endl;
cout << "Attempt to chain streams. This sentence should be printed twice" << endl;


It is not clear for me from the reference manual :

1
2
ostream& operator<< (streambuf* sb);
ostream& operator<< (ostream& ( *pf )(ostream&));
You could do
$ ./program.bin | tee -
Thanks ne555. You are right if I have all the time clog << cout << , but I have also clog << alone.
streams are, in general, single-pass. Once the data went into cout via <<, it can't come back and be re-sent into clog

To split your stream output into multiple sinks, use boost:
1
2
3
4
5
6
7
8
9
10
11
#include <boost/iostreams/tee.hpp>
#include <boost/iostreams/stream.hpp>
#include <iostream>
namespace io = boost::iostreams;
int main()
{
   typedef io::tee_device<std::ostream, std::ostream> dev_t;
   dev_t buf(std::cout, std::clog);
   io::stream<dev_t> str(buf);
   str << "This sentence will be printed twice" << std::endl;
}

Last edited on
Fantastic ! Thanks Cubbi.
Topic archived. No new replies allowed.