【发布时间】:2010-11-12 02:04:30
【问题描述】:
我应该使用哪个函数将文本输出到 Visual Studio 中的“输出”窗口?
我尝试了printf(),但没有出现。
【问题讨论】:
标签: c++ visual-c++
我应该使用哪个函数将文本输出到 Visual Studio 中的“输出”窗口?
我尝试了printf(),但没有出现。
【问题讨论】:
标签: c++ visual-c++
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);
}
【讨论】:
WCHAR szBuff[1024]_vsnwprintf的多字节版本
如果这是用于调试输出,那么 OutputDebugString 就是您想要的。一个有用的宏:
#define DBOUT( s ) \
{ \
std::ostringstream os_; \
os_ << s; \
OutputDebugString( os_.str().c_str() ); \
}
这让你可以说:
DBOUT( "The value of x is " << x );
您可以使用__LINE__ 和__FILE__ 宏对其进行扩展以提供更多信息。
对于 Windows 和宽字符领域的用户:
#include <Windows.h>
#include <iostream>
#include <sstream>
#define DBOUT( s ) \
{ \
std::wostringstream os_; \
os_ << s; \
OutputDebugStringW( os_.str().c_str() ); \
}
【讨论】:
使用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 );
【讨论】:
使用 OutputDebugString 代替 afxDump。
例子:
#define _TRACE_MAXLEN 500
#if _MSC_VER >= 1900
#define _PRINT_DEBUG_STRING(text) OutputDebugString(text)
#else // _MSC_VER >= 1900
#define _PRINT_DEBUG_STRING(text) afxDump << text
#endif // _MSC_VER >= 1900
void MyTrace(LPCTSTR sFormat, ...)
{
TCHAR text[_TRACE_MAXLEN + 1];
memset(text, 0, _TRACE_MAXLEN + 1);
va_list args;
va_start(args, sFormat);
int n = _vsntprintf(text, _TRACE_MAXLEN, sFormat, args);
va_end(args);
_PRINT_DEBUG_STRING(text);
if(n <= 0)
_PRINT_DEBUG_STRING(_T("[...]"));
}
【讨论】:
尽管OutputDebugString 确实向调试器控制台打印了一串字符,但它与printf 并不完全相同,后者能够使用% 表示法和可变数量的参数来格式化参数,一些OutputDebugString 不行。
我会证明_RPTFN 宏,至少带有_CRT_WARN 参数,在这种情况下是一个更好的选择——它格式化主要字符串很像printf,将结果写入调试器控制台。
一个小的(在我看来很奇怪)警告是它需要至少一个参数在格式字符串之后(带有所有%的参数),这是一个限制printf没有受苦。
对于您需要类似puts 的功能的情况——无需格式化,只需按原样写入字符串——有它的兄弟_RPTF0(它忽略了格式字符串后面的参数,这是另一个奇怪的警告)。当然是OutputDebugString。
顺便说一句,还有从_RPT1 到_RPT5 的所有内容,但我还没有尝试过。老实说,我不明白为什么要提供这么多程序都做同样的事情。
【讨论】:
有用的提示 - 如果您使用 __FILE__ 和 __LINE__,则将调试格式设置为:
"file(line): Your output here"
然后,当您在输出窗口中单击该行时,Visual Studio 将直接跳转到该行代码。一个例子:
#include <Windows.h>
#include <iostream>
#include <sstream>
void DBOut(const char *file, const int line, const WCHAR *s)
{
std::wostringstream os_;
os_ << file << "(" << line << "): ";
os_ << s;
OutputDebugStringW(os_.str().c_str());
}
#define DBOUT(s) DBOut(__FILE__, __LINE__, s)
我写了一篇关于这个的博客文章,所以我一直知道我可以在哪里查找它: https://windowscecleaner.blogspot.co.nz/2013/04/debug-output-tricks-for-visual-studio.html
【讨论】:
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
wstring outputMe = L"can" + L" concatenate\n";
OutputDebugString(outputMe.c_str());
【讨论】:
#include <string>