在Visual Studio 2005输出窗口中捕获cout?
时间:2020-03-05 18:56:13 来源:igfitidea点击:
我创建了一个C ++控制台应用程序,只想在Visual Studio 2005 IDE的"输出"窗口中捕获cout / cerr语句。我确定这只是我所缺少的设置。谁能指出我正确的方向?
解决方案
回答
你做不到
如果要输出到调试器的输出窗口,请调用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;
将其魔术化到Visual Studio 2005输出窗口中,作为练习留给Visual Studio 2005插件开发人员。但是我们可能可以通过编写自定义的streambuf类(另请参见boost.iostream)将其重定向到其他位置,例如文件或者自定义窗口。
回答
ben的答案和Mike Dimmick的答案的结合:我们将实现一个stream_buf_,最终调用OutputDebugString。也许有人已经这样做了?看一下两个建议的Boost日志库。
回答
另外,根据意图以及所使用的库,我们可能希望使用TRACE宏(MFC)或者ATLTRACE(ATL)。