# Cout - Custom function

This topic is 4206 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Heya, I'd like to bind all stdout-output to a custom function, for example:
void MyPrint(stringstream & ss) // or whatever; some kind of string of text
{
// Use some device for printing the text
}

...

int main()
{
cout << "abc" << 1 << 2 << 3 << endl; // When the stream is flushed (which should be immediately because of the endl), MyPrint() is called with the argument string "abc123".
}


I have of course googled it but as usual when it comes to C++ streams it only makes me more confused... anyone know if this is possible to do?

##### Share on other sites
There probably is a better C++ way to do this, but it's possible to freopen stdout and use sync_with_stdio. Then you can read the reopened stream and handle it however you want. You can find an example of this in SDL, where all stdio is redirected to stdout.txt and stderr.txt.

This is a bit of a dirty hack, I suggest you find a better way to do this.

However, the simplest solution is to define your own output stream where you write your output. When you don't want your output to be redirected, just make your output a reference to std::cout.

namespace log{#ifndef DEBUGstd::ostream &out = std::cout;std::ostream &err = std::cerr;#elsestd::ostringstream out;std::ostringstream err;#endif};

-Riku

##### Share on other sites
I did a little bit of googling and I found out that you can set std::cout's buffer to your own buffer. You can create a buffer yourself or pick one from a stream, if you want to redirect the output into a file or a stringstream.

#include <iostream>#include <sstream>int main(){	std::stringbuf stringbuf;	std::streambuf *buf = std::cout.rdbuf();	std::cout.rdbuf(&stringbuf);	std::cout << "this goes in the stringbuffer" << std::endl;	std::cout.rdbuf(buf);	std::cout << "contents of the stringbuffer:" << std::endl;	std::cout << stringbuf.str() << std::endl;}

-Riku

##### Share on other sites
You might be able to make use of the discussion in this post.

1. 1
2. 2
Rutin
20
3. 3
khawk
16
4. 4
A4L
14
5. 5

• 11
• 16
• 26
• 10
• 11
• ### Forum Statistics

• Total Topics
633755
• Total Posts
3013706
×