Use std::cout with Unreal Engine Editor
If you are more like traditional C++ programmer rather than fancy Blueprint script user, you will be debugging a lot. Also you will need some basic communication with user, at least to know if programmed functions are returning good outputs. Here comes Output Log Window.
To write anything into Output Log, you need a proper function - most used by me is UE_LOG, better described here. It works most like standard printf function from stdio library: if I want to get standard 'Hello world' text, I type:
UE_LOG(LogTemp,Log,TEXT("Hello world!"));
If we want include any numbers, strings etc, I need to use standard printf syntax: %s for strings, %d for decimals etc. God knows it's not very comfortable, especially when you want to use some more complex functions produced to work with std::cout syntax, like complex numbers or vectors. Also, sometimes we have external functions which don't have access to Unreal libraries, but still give us useful informations to output stream. If we stick to standard UE_LOG syntax, we loose that information.
The solution is to grab the stream from std::cout into custom, user-defined buffer. We will need a sstream library, which contains std::stringbuf class. Now we derive a child class from it - here I called it LStream:
#include <sstream>
//...standard class body
class LStream : public std::stringbuf{
protected:
int sync() {
UE_LOG(LogTemp, Log, TEXT("%s"), *FString(str().c_str()));
str("");
return std::stringbuf::sync();
}
};
Now some explanation - the method int sync() is called every time when program needs to synchronize it's buffer - something we can use, because we would want to get information to output log every time program has something interesting to say. Luckily the original sync() method is virtual, which means it will be overshadowed every time when we make a child class with same method - even if program will treat out buffer as standard stringbuf (or streambuf) - the used method will be written by us. The str(""); function cleans buffer into empty string.
After this operation we can simply redirect the cout stream into our custom made buffer. The method is following - we create simple LString variable and tell the std::cout object to read from our buffer:
LStream Stream;
std::cout.rdbuf(&Stream);
std::cout << "some message" << std::endl;
And voila! Now we have full access to modern iostream output from the level of Unreal Engine editor.
Note - UE_LOG is only a macro for GLog->Log function. You can as well replace all UE_LOG calls with GLog->Log(FString str) calls. Also you can add on-screen debug messages, which is even more usefull during gameplay debugging. For further ideas I send to this page.