在VisualStudio2005输出窗口中捕获cout? 我创建了一个C++控制台应用程序,只想在VisualStudio 2005 IDE的输出窗口中捕获CUT/CERP语句。我肯定这只是我错过的一个环境。有人能给我指出正确的方向吗?

在VisualStudio2005输出窗口中捕获cout? 我创建了一个C++控制台应用程序,只想在VisualStudio 2005 IDE的输出窗口中捕获CUT/CERP语句。我肯定这只是我错过的一个环境。有人能给我指出正确的方向吗?,c++,visual-studio,visual-c++-2005,C++,Visual Studio,Visual C++ 2005,你不能这样做 如果要输出到调试器的输出窗口,请调用OutputDebugString 我发现了一个“teestream”,它允许一个输出到多个流。您可以实现一个向OutputDebugString发送数据的流。这是输出屏幕只是闪烁然后消失的情况吗?如果是这样,您可以使用cin作为返回前的最后一条语句来保持打开状态。您可以像这样捕获cout的输出,例如: std::streambuf* old_rdbuf = std::cout.rdbuf(); std::stringbuf new_rdbuf;

你不能这样做

如果要输出到调试器的输出窗口,请调用OutputDebugString


我发现了一个“teestream”,它允许一个输出到多个流。您可以实现一个向OutputDebugString发送数据的流。

这是输出屏幕只是闪烁然后消失的情况吗?如果是这样,您可以使用cin作为返回前的最后一条语句来保持打开状态。

您可以像这样捕获cout的输出,例如:

std::streambuf* old_rdbuf = std::cout.rdbuf();
std::stringbuf new_rdbuf;
// replace default output buffer with string buffer
std::cout.rdbuf(&new_rdbuf);

// write to new buffer, make sure to flush at the end
std::cout << "hello, world" << std::endl;

std::string s(new_rdbuf.str());
// restore the default buffer before destroying the new one
std::cout.rdbuf(old_rdbuf);

// show that the data actually went somewhere
std::cout << s.size() << ": " << s;
std::streambuf*old_rdbuf=std::cout.rdbuf();
std::stringbuf new_rdbuf;
//将默认输出缓冲区替换为字符串缓冲区
标准::cout.rdbuf(&new_rdbuf);
//写入新缓冲区,确保最后刷新

std::coutben的答案和Mike Dimmick的答案的组合:您将实现一个最终调用OutputDebugString的流。也许有人已经这么做了?请看两个建议的Boost日志库。

此外,根据您的意图和使用的库,您可能希望使用()或()。

我终于实现了这一点,因此我想与您分享:

#include <vector>
#include <iostream>
#include <windows.h>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/tee.hpp>

using namespace std;
namespace io = boost::iostreams;

struct DebugSink
{
    typedef char char_type;
    typedef io::sink_tag category;

    std::vector<char> _vec;

    std::streamsize write(const char *s, std::streamsize n)
    {
        _vec.assign(s, s+n);
        _vec.push_back(0); // we must null-terminate for WINAPI
        OutputDebugStringA(&_vec[0]);
        return n;
    }
};

int main()
{
    typedef io::tee_device<DebugSink, std::streambuf> TeeDevice;
    TeeDevice device(DebugSink(), *cout.rdbuf());
    io::stream_buffer<TeeDevice> buf(device);
    cout.rdbuf(&buf);

    cout << "hello world!\n";
    cout.flush(); // you may need to flush in some circumstances
}

转到输出窗口,然后双击它,然后VisualStudio将跳转到给定的文件第10行,并在状态栏中显示“消息”。它非常有用。

向std::ostrings团队写信,然后跟踪该团队

std::ostringstream oss;

oss << "w:=" << w << " u=" << u << " vt=" << vt << endl;

TRACE(oss.str().data());
std::ostringstream oss;

oss不,你不能,因为单独评估cin没有效果。不需要插件,只需使用Mike Dimmick提到的OutputDebugString。这对我来说效果非常好,但在VS2013和Boost 1.57中,一旦流被刷新,Boost代码中的断言失败就会崩溃,要么通过打印大量内容,要么通过向流发送
std::endl
,使其不再可用:-(不确定这是Boost中的bug还是什么)。
std::ostringstream oss;

oss << "w:=" << w << " u=" << u << " vt=" << vt << endl;

TRACE(oss.str().data());