Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I don't know if this is correct solution, but I inherited from std::ostream this way. It uses a buffer inherited from std::basic_streambuf and gets 64 characters at a time (or less if flushed) and sends them to a generic putChars() method where the actual handling of data is done. It also demonstrates how to give user data.</p> <p><a href="http://ideone.com/AFzNdO" rel="nofollow noreferrer">Live Example</a></p> <pre><code>#include &lt;streambuf&gt; #include &lt;ostream&gt; #include &lt;iostream&gt; //#define DEBUG class MyData { //example data class, not used }; class MyBuffer : public std::basic_streambuf&lt;char, std::char_traits&lt;char&gt; &gt; { public: inline MyBuffer(MyData data) : data(data) { setp(buf, buf + BUF_SIZE); } protected: // This is called when buffer becomes full. If // buffer is not used, then this is called every // time when characters are put to stream. inline virtual int overflow(int c = Traits::eof()) { #ifdef DEBUG std::cout &lt;&lt; "(over)"; #endif // Handle output putChars(pbase(), pptr()); if (c != Traits::eof()) { char c2 = c; // Handle the one character that didn't fit to buffer putChars(&amp;c2, &amp;c2 + 1); } // This tells that buffer is empty again setp(buf, buf + BUF_SIZE); return c; } // This function is called when stream is flushed, // for example when std::endl is put to stream. inline virtual int sync(void) { // Handle output putChars(pbase(), pptr()); // This tells that buffer is empty again setp(buf, buf + BUF_SIZE); return 0; } private: // For EOF detection typedef std::char_traits&lt;char&gt; Traits; // Work in buffer mode. It is also possible to work without buffer. static const size_t BUF_SIZE = 64; char buf[BUF_SIZE]; // This is the example userdata MyData data; // In this function, the characters are parsed. inline void putChars(const char* begin, const char* end){ #ifdef DEBUG std::cout &lt;&lt; "(putChars(" &lt;&lt; static_cast&lt;const void*&gt;(begin) &lt;&lt; "," &lt;&lt; static_cast&lt;const void*&gt;(end) &lt;&lt; "))"; #endif //just print to stdout for now for (const char* c = begin; c &lt; end; c++){ std::cout &lt;&lt; *c; } } }; class MyOStream : public std::basic_ostream&lt; char, std::char_traits&lt; char &gt; &gt; { public: inline MyOStream(MyData data) : std::basic_ostream&lt; char, std::char_traits&lt; char &gt; &gt;(&amp;buf), buf(data) { } private: MyBuffer buf; }; int main(void) { MyData data; MyOStream o(data); for (int i = 0; i &lt; 8; i++) o &lt;&lt; "hello world! "; o &lt;&lt; std::endl; return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload