Reputation: 263
I'm pretty new to C++ and recently switched from compiling in g++ on Linux to Visual Studio. I was trying to write a simple program to test some like this:
#include <iostream>
void main()
{
// Things
}
And I was using cout <<
to display what the function returns, before I realized that it doesn't work this way to print to the output window in Visual Studio. I know I can use the debug mode, but is there a way in Visual Studio to display output to the window? One of the older posts that I found suggested using OutputDebugString, but I didn't write the code as Win32 application, and I think this function doesn't exist for simple cpp files.
Also, is there a reason why a black window pops up when the program is executed, and then immediately disappears?
Upvotes: 3
Views: 16435
Reputation: 3822
If you want to write to an output window from within a unittest case then you can use the following:
#include "CppUnitTest.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
TEST_METHOD(testingsomething)
{
Logger::WriteMessage("Hello output window");
}
Upvotes: 0
Reputation: 54541
Below is a portable TRACE macro I have written.
On Windows, it is based on OutputDebugString
as indicated in WhozCraig's answer.
#ifdef ENABLE_TRACE
# ifdef _MSC_VER
# include <windows.h>
# include <sstream>
# define TRACE(x) \
do { std::stringstream s; s << (x); \
OutputDebugString(s.str().c_str()); \
} while(0)
# else
# include <iostream>
# define TRACE(x) std::clog << (x)
# endif // or std::cerr << (x) << std::flush
#else
# define TRACE(x)
#endif
Example:
#define ENABLE_TRACE // Can depend on _DEBUG or NDEBUG macros
#include "my_above_trace_header.h"
int main (void)
{
int v1 = 123;
double v2 = 456.789;
TRACE ("main() v1="<< v1 <<" v2="<< v2 <<'\n');
}
Upvotes: 2
Reputation: 66194
OutputDebugString for the win. It does exists. Just include windows.h. It's there.
There are ways to effectively wire stderr and stdout to a pipe and have you resink the output to OutputDebugString, but it sounds like you're looking for a simple way. Anything written to stdout (cout, whatever) will go to the console window, so before you go OutputDebugString nuts check your console window first for your output...
Speaking of console window...
The reason black pops up and immediately disappears is your console window is opening and closing, and chances are your process is finishing before anything substantial is done. Jam a breakpoint at the end of main() in the IDE. You can then Alt + Tab to it.
BTW: if you go with OutputDebugString, it does NOT CRLF the text you send, so include that in your output text.
Upvotes: 4