如何在非控制台应用程序中看到cout输出?

How can I see cout output in a non-console application?

本文关键字:cout 输出 应用程序 控制台      更新时间:2023-10-16

输出到调试窗口似乎相当乏味。如果我正在编写非控制台信息,我在哪里可以找到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");