title: Redirecting cout to a console in windows
body: <p>I have an application which is a relatively old. Through some minor changes, it builds nearly perfectly with Visual C++ 2008. One thing that I've noticed is that my "debug console" isn't quite working right. Basically in the past, I've use <code>AllocConsole()</code> to create a console for my debug output to go to. Then I would use <code>freopen</code> to redirect <code>stdout</code> to it. This worked perfectly with both C and C++ style IO.</p>
  
  <p>Now, it seems that it will only work with C style IO. What is the proper way to redirect things like <code>cout</code> to a console allocated with <code>AllocConsole()</code>?</p>
  
  <p>Here's the code which used to work:</p>
  
  <pre><code>if(AllocConsole()) {
      freopen("CONOUT$", "wt", stdout);
      SetConsoleTitle("Debug Console");
      SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED);
  }
  </code></pre>
  
  <p><strong>EDIT</strong>: one thing which occurred to me is that I could make a custom streambuf whose overflow method writes using C style IO and replace <code>std::cout</code>'s default stream buffer with it. But that seems like a cop-out. Is there a proper way to do this in 2008? Or is this perhaps something that MS overlooked?</p>
  
  <p><strong>EDIT2</strong>: OK, so I've made an implementaiton of the idea I spelled out above. Basically it looks like this:</p>
  
  <pre><code>class outbuf : public std::streambuf {
  public:
      outbuf() {
          setp(0, 0);
      }
  
      virtual int_type overflow(int_type c = traits_type::eof()) {
          return fputc(c, stdout) == EOF ? traits_type::eof() : c;
      }
  };
  
  int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {
      // create the console
      if(AllocConsole()) {
          freopen("CONOUT$", "w", stdout);
          SetConsoleTitle("Debug Console");
          SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED);  
      }
  
      // set std::cout to use my custom streambuf
      outbuf ob;
      std::streambuf *sb = std::cout.rdbuf(&amp;ob);
  
      // do some work here
  
      // make sure to restore the original so we don't get a crash on close!
      std::cout.rdbuf(sb);
      return 0;
  }
  </code></pre>
  
  <p>Anyone have a better/cleaner solution than just forcing <code>std::cout</code> to be a glorified <code>fputc</code>?</p>