Redirect ostringstream to console?

Jul 11, 2012 at 4:58am
I have a DLL which uses AllocConsole() to create a new console window.
I would like to use an ostringstream to print out information to this console like so:

1
2
ostringstream s;
s << "This should display within the console" << endl;


I also have file streams which are not meant to be redirected to this window, so how can this be done without interfering?
Last edited on Jul 11, 2012 at 5:01am
Jul 11, 2012 at 5:07am
An ostringstream isn't meant to be directed to the console. It's meant to take in data and turn it into a string. You could do something like this:

1
2
std::ostream& s = /*get output stream*/;
//... 


I don't know if std::cout is bound to that when you use AllocConsole()...You might be stuck writing a wrapper class that acts like a stream but uses some Windows stuff internally to write to your AllocConsole()'d output handle.
Jul 11, 2012 at 5:15am
Okay, so how would you redirect an ostream to a window created using AllocConsole()?
Basically, I don't want to use cout to do this, and don't want any interference with my file streams.
Last edited on Jul 11, 2012 at 5:15am
Jul 11, 2012 at 12:15pm
Why don't you want to use cout? If you want to make ostringstream print to the console, do this:
1
2
3
#include <iostream>
//do NOT include <sstream>!!
typedef ostream ostringstream
Last edited on Jul 11, 2012 at 12:23pm
Jul 11, 2012 at 1:51pm
> how would you redirect an ostream to a window created using AllocConsole()?

As one would redirect any stream - by changing the associated streambuf.

For example, using boost::file_descriptor_sink

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <windows.h>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <sstream>

bool redirect_ostream_to_stdout( std::ostream& ostm )
{
    using namespace boost::iostreams ;
    static auto fd = GetStdHandle(STD_OUTPUT_HANDLE) ;
    if( fd == INVALID_HANDLE_VALUE ) return false ;
    static file_descriptor_sink stdout_sink( fd, never_close_handle ) ;
    static stream<file_descriptor_sink> stdout_stm(stdout_sink) ;

    ostm.rdbuf( stdout_stm.rdbuf() ) ;
    return ostm ;
}

int __stdcall WinMain( HINSTANCE, HINSTANCE, char*, int )
{
    AllocConsole() ;

    std::ostringstream strstm ;
    redirect_ostream_to_stdout(strstm) ;
    strstm << "hello world!" << std::endl ;

    Sleep(5000) ;
    return !strstm ;
}

Last edited on Jul 11, 2012 at 1:51pm
Topic archived. No new replies allowed.