Cheshire Cat Cheshire Cat - 2 months ago 9
C++ Question

std::cout, ostream and other kinds of getting output stream

In my project (Unreal Engine 4) I don't have an output stream - instead of this I can communicate via UE_LOG function, which works pretty much similar to

printf()
. The problem is that I just made a .dll library (without Unreal includes) which I want to communicate through the
iostream
. My idea is - inside .dll library I use standard
cout
to write messages into ostream, I use all of it in Unreal Engine functions, where I grab
ostream
in form of string and output it into UE_LOG function.

Problem is I always treated
std::cout
as a part of magic, without thinking what is really inside (I am pretty sure most of us did). How I can handle this? Easy ways won't work (like grabbing
stringstream
and outputing it into UE_LOG).

Answer

My idea is - inside .dll library I use standard cout to write messages into ostream

You actually can replace the output buffer used with std::cout with your own implementation. Use the std::ostream::rdbuf() function to do so (example from the reference docs):

#include <iostream>
#include <sstream>

int main()
{
    std::ostringstream local;
    auto cout_buff = std::cout.rdbuf(); // save pointer to std::cout buffer

    std::cout.rdbuf(local.rdbuf()); // substitute internal std::cout buffer with
        // buffer of 'local' object

    // now std::cout work with 'local' buffer
    // you don't see this message
    std::cout << "some message";

    // go back to old buffer
    std::cout.rdbuf(cout_buff);

    // you will see this message
    std::cout << "back to default buffer\n";

    // print 'local' content
    std::cout << "local content: " << local.str() << "\n";
}
Comments