It seems rather tedious to output to debug window. Where can I find cout
output if I am writing a non-console information ?
Like:
double
I'd like to give my 2 cents.
Given that the maybe is a VS issue about compliancy with the C++ standard or that we could use OutputDebugStringA
, if you cannot modify your code base you may like the idea of simply redirect the std::cout to something else, like a file.
So without changing your code base you can do something like suggested here:How to redirect cin and cout to files?
Condensed:
#include <fstream>
std::ofstream out("out.txt"); std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!
std::cout.rdbuf(coutbuf); //reset to standard output again
Hope this may help someone, Kudos to Nawaz that provided the answer in the other thread.
To output a string to the debug console, use OutputDebugStringA
. See http://msdn.microsoft.com/en-us/library/windows/desktop/aa363362%28v=vs.85%29.aspx
To output variable values to the debug console, using std::ostringstream
, the send the string to OutputDebugStringA
.
Excessive output statements will cause the program to severly slow down. However, it is a good technique to catch things the debugger has a problem with, such as the actual child members when playing with base pointers.
The question is very clear. How use std::cout to debug a non-console application in Visual Studio.
The answer is very clear: you cannot. That is, Visual Studio does not support std::cout as debug tool for non-console applications.
This is a serious limitation of Visual Studio, probably a failure to meet the C++ standard even. I find it very sad to see disinformative "answers" here trying to hide this defect of their precious Visual Studio.
SOLUTION: This answer solves the question and allows you to redirect console output to the Visual Studio Output window. First we need a class that overrides the default cout string stream:
class dbg_stream_for_cout
: public std::stringbuf
{
public:
~dbg_stream_for_cout() { sync(); }
int sync()
{
::OutputDebugStringA(str().c_str());
str(std::string()); // Clear the string buffer
return 0;
}
};
dbg_stream_for_cout g_DebugStreamFor_cout;
Then, somewhere you want to "activate" writing to the VS output window:
std::cout.rdbuf(&g_DebugStreamFor_cout); // Redirect std::cout to OutputDebugString!
You can use .Net functions such as System::Diagnostics::Debug::WriteLine("your message"). You can even add a condition to print only during the debug mode and not in the release mode. For example:
#ifdef DEBUG
System::Diagnostics::Debug::WriteLine("your message");
#endif
For a Windows solution, you can allocate a console, and bind cout/cin to it. For example:
AllocConsole();
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
Documentation:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms681944%28v=vs.85%29.aspx