Redirect std::cout to newly created console [duplicate]
When you create a C++ console application under Windows you automatically get the console window created for you and std::cout outputs to the console window.
I have a GUI application for which I also want to create a console window. I can create the console window using the AllocConsole() function, but how do I redirect / attach std::cout to the console so that the output appears in the console window?
You want to use the GetStdHandle and SetStdHandle. Given that it is a long, long time since I have done anything similar, you would be better looking at some Some examples
There is also this duplicate question
As far as I know you can't redirect the standard handles to the new console. You'll have to call GetStdHandle(DWORD) to get a handle for each device you want to write to. Using this handle you'll need to call the WriteFile, ReadFile, WriteConsole and ReadConsoleInput functions with the appropriate handle to pass data back and forth.
精彩评论