2008-09-16 100 views

回答

6

你不能這樣做。

如果要輸出到調試器的輸出窗口,請調用OutputDebugString。

我發現了'teestream'的this implementation,它允許一個輸出去多個流。您可以實現將數據發送到OutputDebugString的流。

+1

-1,錯。看到本的回答。 – MSalters 2010-08-20 07:27:35

1

這是輸出屏幕閃爍然後消失的情況嗎?如果是這樣的話,你可以在返回之前用cin作爲你最後的語句來保持它的打開狀態

+0

不,你不能因爲自己評估cin沒有效果。 – ben 2008-09-16 21:20:08

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; 

Magicking它到Visual Studio 2005輸出窗口留作鍛鍊到了Visual Studio 2005的插件開發者。但是你可能可以將它重定向到其他地方,比如文件或自定義窗口,也許可以通過編寫一個自定義的streambuf類來實現(另請參閱boost.iostream)。

+3

不需要插件,只需使用Mike Dimmick提到的OutputDebugString即可。 – jwfearn 2008-09-26 13:58:47

2

Ben的答案和Mike Dimmick's的結合:你將實現一個stream_buf_,最終調用OutputDebugString。也許有人已經這樣做了?看看兩個建議的Boost日誌庫。

+0

這看起來像這樣:http://www.codeproject.com/KB/debug/debugout.aspx – wimh 2011-03-09 22:17:59

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

這對我來說工作得非常好,但對於VS2013和Boost 1.57,它在Boost代碼中聲明失敗時崩潰,因爲一旦流被刷新,無論是通過打印或發送`std :: endl`到流中,所以它不再可用:-(不知道它是否是Boost中的錯誤或什麼。 – Malvineous 2015-01-18 23:38:19

相關問題