title: Correctly over-loading a stringbuf to replace cout in a MATLAB mex file
body: <p>MathWorks currently doesn't allow you to use <code>cout</code> from a mex file when the MATLAB desktop is open because they have redirected stdout.  Their current workaround is providing a function, <a href="http://www.mathworks.com/support/tech-notes/1600/1605.html" rel="nofollow noreferrer">mexPrintf, that they request you use instead</a>.  After googling around a bit, I think that it's possible to extend the <code>std::stringbuf</code> class to do what I need.  Here's what I have so far.  Is this robust enough, or are there other methods I need to overload or a better way to do this?  (Looking for portability in a general UNIX environment and the ability to use <code>std::cout</code> as normal if this code is not linked against a mex executable)</p>
  
  <pre><code>class mstream : public stringbuf {
  public:
    virtual streamsize xsputn(const char *s, std::streamsize n) 
    {
  mexPrintf("*s",s,n);
  return basic_streambuf&lt;char, std::char_traits&lt;char&gt;&gt;::xsputn(s,n);
    }
  }; 
  
  mstream mout;
  outbuf = cout.rdbuf(mout.rdbuf());    
  </code></pre>