Formatted Debugger Output
Index
If you've ever wanted to use <iostream> style output to get text to your Win32 debugger window, then this is the tip for you!
Normally, to get formatted text into your debugger, you need to use sprintf or one of its equivalents, then take the resulting
string and pass it to OutputDebugString. This is incredibly painful and ugly in code.
Our approach is to tweak the Standard C++ library to let us write code of the form:
dbg << "A message!" << endl;
Anyway, here's the code:
/* - debug.h - */
#include
extern std::ostream dbg; // client code doesn't need to know anything else about how dbg works!
/* - debug.cpp - */
#include "debug.h"
class debugger_streambuf : public std::streambuf
{
public:
typedef std::streambuf inherited;
public:
virtual int sync();
virtual int overflow( int nCh = EOF );
virtual int doallocate();
private:
std::string m_buffer;
};
int debugger_streambuf::sync()
{
const char* _cstr = m_buffer.c_str( );
if ( _cstr )
{
OutputDebugString( _cstr );
}
m_buffer.resize( 0 );
doallocate( );
return 0;
}
int debugger_streambuf::overflow( int nCh )
{
sync( );
if ( nCh != EOF )
{
m_buffer[0] = char( nCh );
pbump( 1 );
}
return 0;
}
int debugger_streambuf::doallocate()
{
m_buffer.resize( MAX_PATH );
inherited::setp( m_buffer.begin( ) , m_buffer.end( ) );
return MAX_PATH;
}
static debugger_streambuf dbg_buf;
std::ostream dbg( &dbg_buf ); // hook up the debugger ostream object to our debugger_streambuf.