首页 / 知识

关于c ++:在Visual Studio 2005输出窗口中捕获cout?

2023-04-15 23:46:00

关于c ++:在Visual Studio 2005输出窗口中捕获cout?

Capturing cout in Visual Studio 2005 output window?

我创建了一个C ++控制台应用程序,只想在Visual Studio 2005 IDE的"输出"窗口中捕获cout / cerr语句。 我确定这只是我所缺少的设置。 谁能指出我正确的方向?


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#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!
"
;
    cout.flush(); // you may need to flush in some circumstances
}

奖励提示:如果您写:

1
2
X:\full\file
ame.txt(10) : message

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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)。


你做不到

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

我发现了这种" teestream"的实现,它允许一个输出进入多个流。您可以实现将数据发送到OutputDebugString的流。


ben的答案和Mike Dimmick的答案的结合:您将实现一个stream_buf_,最终调用OutputDebugString。也许有人已经这样做了?看一下两个建议的Boost日志库。


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


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

1
2
3
4
5
std::ostringstream oss;

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

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


另外,根据您的意图以及所使用的库,您可能希望使用TRACE宏(MFC)或ATLTRACE(ATL)。


输出语句应用程序控制台

最新内容

相关内容

猜你喜欢