Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing cout in Visual Studio 2005 output window?

I created a C++ console app and just want to capture the cout/cerr statements in the Output Window within the Visual Studio 2005 IDE. I'm sure this is just a setting that I'm missing. Can anyone point me in the right direction?

like image 493
billcoke Avatar asked Sep 16 '08 14:09

billcoke


People also ask

How do I display the output window in Visual Studio?

To display the Output window whenever you build a project, in the Options dialog box, on the Projects and Solutions > General page, select Show Output window when build starts.

How do I minimize the output window in Visual Studio?

You can use Shift + Esc to close any tool window. to bring a tool window you can use the shortcuts like Ctrl+W ...

Does cout stand for console out?

cout stands for console or character output, which is by default is directed to standard output.


1 Answers

I've finally implemented this, so I want to share it with you:

#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
}

BONUS TIP: If you write:

X:\full\file\name.txt(10) : message

to the output window and then double-click on it, then Visual Studio will jump to the given file, line 10, and display the 'message' in status bar. It's very useful.

like image 137
Yakov Galka Avatar answered Oct 07 '22 01:10

Yakov Galka