在Visual Studio 2005输出窗口中捕获cout?

时间:2008-09-16 14:59:51

标签: c++ visual-studio visual-c++-2005

我创建了一个C ++控制台应用程序,只想捕获Visual Studio 2005 IDE中输出窗口中的cout / cerr语句。我敢肯定,这只是一个我不知道的环境。有人能指出我正确的方向吗?

7 个答案:

答案 0 :(得分:14)

我终于实现了这个,所以我想与你分享:

#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
}

奖金提示:如果你写:

X:\full\file\name.txt(10) : message

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

答案 1 :(得分:8)

您可以像这样捕获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;

将其引入Visual Studio 2005输出窗口留给Visual Studio 2005插件开发人员。但你可以将它重定向到其他地方,比如文件或自定义窗口,也许是通过编写自定义的streambuf类(另请参见boost.iostream)。

答案 2 :(得分:6)

你不能这样做。

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

我找到了'teestream'的this implementation,它允许一个输出转到多个流。您可以实现将数据发送到OutputDebugString的流。

答案 3 :(得分:2)

Ben的答案和Mike Dimmick的组合:你将实现一个最终调用OutputDebugString的stream_buf_。也许有人已经这样做了?看看两个提议的Boost日志库。

答案 4 :(得分:1)

这是输出屏幕只是闪烁然后消失的情况吗?如果是这样,你可以在返回之前使用cin作为你的最后一句话来保持开放。

答案 5 :(得分:0)

此外,根据您的意图以及您使用的库,您可能需要使用TRACE macroMFC)或ATLTRACEATL)。< / p>

答案 6 :(得分:0)

写入std :: ostringsteam,然后对其进行跟踪。

std::ostringstream oss;

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

TRACE(oss.str().data());
相关问题