如何在Visual Studio中写入"输出"窗口?

cla*_*amp 73 c++ visual-c++

我应该使用哪个函数将文本输出到Visual Studio中的"输出"窗口?

我试过printf()但它没有显示出来.

Sor*_*tis 78

OutputDebugString函数会做到这一点.

示例代码

    void CClass::Output(const char* szFormat, ...)
{
    char szBuff[1024];
    va_list arg;
    va_start(arg, szFormat);
    _vsnprintf(szBuff, sizeof(szBuff), szFormat, arg);
    va_end(arg);

    OutputDebugString(szBuff);
}
Run Code Online (Sandbox Code Playgroud)

  • 我收到一个错误,szBuff无法使用LPCWSTR类型 (4认同)
  • 这还有一个问题._vsnprintf可能会截断格式化的字符串以适应缓冲区,但如果发生这种情况,字符串将不会以空字符结尾.请参阅http://msdn.microsoft.com/en-us/library/1kt27hek.aspx和http://stackoverflow.com/questions/357068. (3认同)

小智 72

如果这是用于调试输出,那么OutputDebugString就是你想要的.一个有用的宏:

#define DBOUT( s )            \
{                             \
   std::ostringstream os_;    \
   os_ << s;                   \
   OutputDebugString( os_.str().c_str() );  \
}
Run Code Online (Sandbox Code Playgroud)

这允许你说:

DBOUT( "The value of x is " << x );
Run Code Online (Sandbox Code Playgroud)

您可以使用__LINE____FILE__宏扩展它以提供更多信息.

对于那些在Windows和广泛的土地:

#include <Windows.h>
#include <iostream>
#include <sstream>

 #define DBOUT( s )            \
{                             \
   std::wostringstream os_;    \
   os_ << s;                   \
   OutputDebugStringW( os_.str().c_str() );  \
}
Run Code Online (Sandbox Code Playgroud)

  • @sami1592这两个宏由编译器定义为(惊讶)行和文件,因此您可以自动输出包含行和文件的更多有用日志. (2认同)

Reu*_*nen 19

使用OutputDebugString功能或TRACE宏(MFC),您可以进行printf格式化:

int x = 1;
int y = 16;
float z = 32.0;
TRACE( "This is a TRACE statement\n" );    
TRACE( "The value of x is %d\n", x );
TRACE( "x = %d and y = %d\n", x, y );
TRACE( "x = %d and y = %x and z = %f\n", x, y, z );
Run Code Online (Sandbox Code Playgroud)