Jump to content
  • Advertisement
Sign in to follow this  
olle hakansson

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.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 DEBUG
std::ostream &out = std::cout;
std::ostream &err = std::cerr;
#else
std::ostringstream out;
std::ostringstream err;
#endif
};


-Riku

Share this post


Link to post
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!