Prev: Generic compare function
Next: reasoning of ::std::cout (ostream) conversion w.r.t. plain, signed and unsigned chars...
From: Larry Evans on 19 Jan 2010 21:14 On Jan 18, 8:43 am, "dietmar_ku...(a)yahoo.com" <dietmar.ku...(a)gmail.com> wrote: [snip] > A much > more sensible (and much easier to implement) approach is to create a > filtering stream buffer which just replaces every newline by a newline > followed by the appropriate number of spaces. In its simplest form > (non-optimized) form it just takes a few lines of code: > > struct indentbuf: std::streambuf > { > indentbuf(std::streambuf* sbuf, int indent): > m_sbuf(sbuf), m_indent(indent) {} > private: > int_type overflow(int_type c) > { > if (c != std::char_traits::eof()) > { > this->m_sbuf->sputc(c); > if (c == '\n') > { > std::fill_n(std::ostreambuf_iterator<char>(this->m_sbuf), > this->m_indent, ' '); > } > } > return std::char_traits::not_eof(c); > } > int sync() { return this->m_sbuf->pubsync(); } > std::streambuf* m_sbuf; > int m_indent; > }; > > You'd create a new std::ostream with using something like this: > > indentbuf sbuf(std::cout.rdbuf(), 2); > std::ostream indentstream(&sbuf); > > Obviously, if you want to use indentation with an existing stream you > can replace that stream's stream buffer with an indentbuf as long as > objects get the proper live time. [snip] You'd also need a way to change indentbuf::m_indent. This would require using rdbuf() and then casting to indentbuf*. Althought boost/iostreams has (I assume) a lot of overhead, this is done automatically in the boost vault code mentioned in my post. I would guess the iostreams implementation does something like your suggestion behind the scenes since the acknowledgments: http://www.boost.org/doc/libs/1_41_0/libs/iostreams/doc/acknowledgments.html mention your and Kanze's names. -regards, Larry -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Larry Evans on 19 Jan 2010 21:15
On Jan 18, 8:43 am, "dietmar_ku...(a)yahoo.com" <dietmar.ku...(a)gmail.com> wrote: [snip] > Obviously, if you want to use indentation with an existing stream you > can replace that stream's stream buffer with an indentbuf as long as > objects get the proper live time. [snip] I believe this is illustrated by the indent_scoped_ostreambuf.zip file in the boost vault directory: http://www.boostpro.com/vault/index.php?&directory=Input%20-%20Output -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |