如何在非控制台应用程序中看到cout输出?
How can I see cout output in a non-console application?
输出到调试窗口似乎相当乏味。如果我正在编写非控制台信息,我在哪里可以找到cout
输出?
:
double i = a / b;
cout << b << endl;//I want to check out whether b is zero. It seems the output cannot be found anywhere.
这个问题很清楚。如何在Visual Studio中使用std::cout调试非控制台应用程序。
答案很清楚:你不能。也就是说,Visual Studio不支持std::cout作为非控制台应用程序的调试工具。
这是Visual Studio的一个严重限制,甚至可能不符合c++标准。看到这些不实的"答案"试图掩盖他们宝贵的Visual Studio的缺陷,我感到非常难过。
对于Windows解决方案,您可以分配一个控制台,并将cout/cin绑定到它。例如:
AllocConsole();
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
文档:https://msdn.microsoft.com/en-us/library/windows/desktop/ms681944%28v=vs.85%29.aspx
解决方案:这个答案解决了这个问题,并允许您将控制台输出重定向到Visual Studio输出窗口。首先,我们需要一个类来覆盖默认的cout字符串流:
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;
然后,在你想要"激活"写入VS输出窗口的地方:
std::cout.rdbuf(&g_DebugStreamFor_cout); // Redirect std::cout to OutputDebugString!
要向调试控制台输出字符串,请使用OutputDebugStringA
。见http://msdn.microsoft.com/en-us/library/windows/desktop/aa363362%28v=vs.85%29.aspx
将变量值输出到调试控制台,使用std::ostringstream
,将字符串发送到OutputDebugStringA
。
过多的输出语句将导致程序严重减速。但是,这是一种很好的技术,可以捕获调试器存在的问题,例如在处理基指针时实际的子成员。
我想捐点钱。
考虑到这可能是一个VS问题,关于遵守c++标准,或者我们可以使用OutputDebugStringA
,如果你不能修改你的代码库,你可能喜欢简单地将std::cout重定向到其他东西,比如一个文件。
所以不改变你的代码库,你可以做一些像这里建议的:如何重定向cin和cout到文件?
浓缩:
- 添加包含
#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!
- 在你的应用程序的结尾/logging:
std:: cout.rdbuf (coutbuf);//重新设置为标准输出
希望这能帮助到一些人,向Nawaz致敬,他在另一个帖子中提供了答案
不使用cout,而是创建一个日志文件,并在其中写入任何您想要的内容。
编辑:使用下面的简单代码写入日志文件。
ofstream log;
log.open ("log.txt");
log << "Writing this to a file.n";
log.close();
您可以使用。net函数,如System::Diagnostics::Debug::WriteLine("your message")。您甚至可以添加一个条件,只在调试模式而不是发布模式下打印。例如:
#ifdef DEBUG
System::Diagnostics::Debug::WriteLine("your message");
#endif
是的,确实很烦人。
我是这样做的:
#define DBOUT( s )
{
std::wostringstream os_;
os_ << s;
OutputDebugStringW( os_.str().c_str() );
}
// example : DBOUT("some text " << some_variable << " some more text" << some_other_varaible << "n");
- std::cout输出int时出现编译错误
- 为什么'std::cout << !+2 '输出 0?
- 在视觉工作室中以十六进制进行位移位并通过 cout 输出
- 为什么cout输出内存地址不是字符串?
- 如何在c++中将方法的cout输出输出到流文件中
- cout 输出乱码消息行,而不是实际用户的 cout 语句
- 如何在运行时禁用COUT输出
- bool:不正确的cout输出,而不是0或1
- "cout << cout" - 输出代表什么?
- Xcode调试器未显示C++cout输出
- 为什么 std::cout 输出溢出
- 为什么我的 cout 输出没有立即显示
- 在C++中格式化 Cout 输出
- 是否可以在C++中的文件中显示void函数cout输出
- 同步STD cout输出多线程
- 用visual studio和C++/OpenGL进行cout输出
- std::cout输出直到程序结束才打印
- 如何在非控制台应用程序中看到cout输出?
- 使用SDL时没有从cout输出
- 为什么std::cout输出在发送NULL后完全消失?