How to output std::cout to Visual Studio Output Window?

Viewed 33

I was trying to find a simple way to redirect std::cout outputs to the Visual Studio console window, so that the same code can be used to log on Mac and Windows.

1 Answers

After an hour of searching, I finally found a simple way that works (mostly based on https://stackoverflow.com/a/51498216/3311183)

At the start of my program, I put:

#ifdef _WIN32
#include <ostream>
#include <Windows.h>
#include <string>
#include <sstream>
#endif

And then at the start of any function that I want to redirect std::cout in (i.e. at the top of my main function), I put:

#ifdef _WIN32
std::streambuf* backup;
backup = std::cout.rdbuf();
std::stringstream ss;
std::cout.rdbuf(ss.rdbuf());
#endif

Then, at the bottom of that function (i.e. at the end of my program), I put:

#ifdef _WIN32
OutputDebugString(ss.str().c_str());
std::cout.rdbuf(backup);
#endif

That's it!

Related