bil*_*oke 17 c++ visual-studio visual-c++-2005
我创建了一个C++控制台应用程序,只想在Visual Studio 2005 IDE中的输出窗口中捕获cout/cerr语句.我敢肯定,这只是一个我不知道的环境.谁能指出我正确的方向?
ybu*_*ill 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
}
Run Code Online (Sandbox Code Playgroud)
奖金提示:如果你写:
X:\full\file\name.txt(10) : message
Run Code Online (Sandbox Code Playgroud)
到输出窗口,然后双击它,然后Visual Studio将跳转到给定的文件,第10行,并在状态栏中显示"消息".这非常有用.
您可以像这样捕获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;
Run Code Online (Sandbox Code Playgroud)
将其引入Visual Studio 2005输出窗口,这是对Visual Studio 2005插件开发人员的练习.但你可以将它重定向到其他地方,比如文件或自定义窗口,也许是通过编写自定义streambuf类(另请参阅boost.iostream).
| 归档时间: |
|
| 查看次数: |
15301 次 |
| 最近记录: |