    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Writing Your Own Stream Manipulators</title>
        <link>https://members.accu.org/index.php/journals/1769</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #5 - Sep 1994 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c308/">05</a>
                    (11)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c308-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c308+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Writing Your Own Stream Manipulators</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 12 May 2012 21:20:42 +01:00 or Sat, 12 May 2012 21:20:42 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<!-- Page 16 -->

<p><em>Still glides the Stream, and shall for ever glide;<br />The Form remains, the Function never dies.</em><br />William Wordsworth</p>
<p>Streams are typically more than just dumping or loading grounds for basic data. Their strength lies in accommodation of new data types and customisation. As objects their state may also be controlled via either a method or a manipulator interface; I am going to concentrate on manipulators. Iâ€™ll wrap up the article with a worked example.</p>
<h2>Simple manipulators</h2>
<p>Data flow and control are the two basic operations on a stream. Returning references and the syntactic sugar of operator overloading offer a convenient way to chain together successive items for input or output in a single expression:</p>
<pre class="programlisting"><code>clog reason &quot; (error &quot; &lt;&lt; errno &quot;'): &quot; &lt;&lt; strerror(errno) &lt;&lt; endl;</code></pre>
<p>The last item in the above expression provides more control than data: a newline is inserted and the buffered output is flushed. Using the endl stream manipulator is a more common idiom than using a naked in â€™\nâ€™ C++. The equivalent expression without manipulators is slightly less elegant:</p>
<pre class="programlisting"><code>(clog &lt;&lt; reason &lt;&lt; &quot; (error &quot; &lt;&lt; errno &quot;): &quot; &lt;&lt; strerror(errno) &lt;&lt; '\n').flush();</code></pre>
<p>Other simple manipulators include: ws, to act as a sink and eat whitespace from an istream; ends, to <em>NUL</em> terminate a string; flush, to flush an ostream; and hex, dec and oct, to convert input from and output to the appropriate base.</p>
<p>These are all simply function names. In addition to the insertion and extraction member operators for basic types, the istream and ostream classes both have operators that take a function pointer to execute on the current stream.</p>
<p>Given this, it is possible to define your own manipulators to control layout and stream state: (See listing 1)</p>
<table class="sidebartable"><tr><td>

<pre class="programlisting"><code>ostream &amp;tab(ostream &amp;out)
{
    return out Â« '\t';
}

ostream &amp;title(ostream &amp;out)
{
    return out &lt;&lt; &quot;\n&quot;
                  &quot;********************\n&quot;
                  &quot;* Objects R Us Ltd *\n&quot;
                  &quot;********************\n&quot;
               &lt;&lt; endl;
}

istream &amp;eatline(istream &amp;in)
{
    while(in &amp;&amp; in.get() != '\n')
    {
    }
    return in;
}</code></pre>
</td></tr><tr><td class="title">
Listing 1 - layout and state manipulators
</td></tr></table>

<p>These manipulators may be used both indirectly and directly:</p>
<pre class="programlisting"><code>cin &gt;&gt; eatline;
eatline(cin);</code></pre>
<p>The indirect form offers the syntactic convenience of mixing control and data into a sequence of insertions or extractions from a stream.</p>
<h2>Parameterised manipulators</h2>
<p>All the manipulators shown above are simple functions. They perform a single task well but without any flexibility. A standard <em>IOStream</em> implementation also provides a number of manipulators taking the form of function calls to control the stream. For instance to set the output precision for floating point numbers:</p>
<!-- Page 17 -->

<pre class="programlisting"><code>cout &lt;&lt; &quot;result = &quot;
     &lt;&lt; setprecision(6)
     &lt;&lt; result
     &lt;&lt; endl;</code></pre>
<p>Using this approach you can implement more general control over the stream: (See listing 2)</p>
<table class="sidebartable"><tr><td>

<pre class="programlisting"><code>cout &lt;&lt; newline(5); //five newlines and a flush
cout &lt;&lt; newpage(standard_title);
cin &gt;&gt; eat('*');</code></pre>
</td></tr><tr><td class="title">
Listing 2 - more control
</td></tr></table>

<p>There are a number of different methods for implementing these manipulators. The most obvious method is to implement these manipulators as functions that return objects for which insertion or extraction operators are defined, eg. (See listing 3)</p>
<table class="sidebartable"><tr><td>

<pre class="programlisting"><code>class eatable
{
public:
    eatable(char);
} ;

istream &amp;operator&gt;&gt;(istream &amp;, eatable);

eatable eat(char to_eat)
(
    return eatable(to_eat);
}</code></pre>
</td></tr><tr><td class="title">
Listing 3 - class eatable
</td></tr></table>

<p>Such classes are often not intended for general use and have mangled names or friend only access. A more direct and, in my opinion, more general solution is to cut out the function and use objects directly. A constructor call to create a temporary object looks like a function call with much the same effect:</p>
<pre class="programlisting"><code>class eat
{
public:
   eat(char);
   ...
};
istream &amp;operator&gt;&gt;(istream &amp;, eat);</code></pre>
<p>The class based approach offers a more obvious route to creating custom manipulator objects:</p>
<pre class="programlisting"><code>eat line_sink('\n');
separator_sink(separator);
cin &gt;&gt; line_sink;
cin &gt;&gt; separator_sink;</code></pre>
<p>Objects can act as pseudo-functions or functors. This is a powerful idiom deriving from use of the function call operator, so that direct application of manipulators on streams becomes possible:</p>
<pre class="programlisting"><code>eat_line(cin);
eat_separator(cin);</code></pre>
<p>This is an idiom I will return to and explore in greater detail in future.</p>
<h2>An example</h2>
<p>Consider a manipulator that takes an integer and expands it out into word form, eg.</p>
<pre class="programlisting"><code>cout &lt;&lt; expand(-123) &lt;&lt; endl;</code></pre>
<p>will print out</p>
<p><strong>minus one hundred and twenty three</strong></p>
<p>The class holds a single value and is not designed as a base class, so the default copy constructor, assignment operator and destructor are usable â€” they may be inserted for completeness, but for the sake of brevity I will omit them from this article: (See listing 4)</p>
<table class="sidebartable"><tr><td>

<pre class="programlisting"><code>class expand
{
public:
    expand(short to_expand) : value (to_expand) {}
    ostream &amp;operator()(ostream &amp;) const;
private:
    short value;
    static const char *const tens[];
    static const char *const units_and_teens[];
};</code></pre>
</td></tr><tr><td class="title">
Listing 4 - class expand
</td></tr></table>

<p>The operator() member function does the hard work, using the literal constant tables tens (â€œtenâ€ to â€œninetyâ€, starting from the first element rather than the zeroth) and units_and_teens (â€œ zeroâ€ to â€œnineteenâ€). This makes the stream insertion operator quite trivial:</p>
<pre class="programlisting"><code>ostream &amp;operator &lt;&lt;(ostream &amp;out, expand number)
{
   return number(out);
}</code></pre>
<p>Notice also that friendship of the class is not required for the insertion operator; the property of expression on an ostream is a feature of the class and may be used separately. The algorithm for writing out the number is mutually recursive.</p>
<p>You are welcome to try a non-recursive version if you wish, but you will gain little except a fuller understanding of why the simplest solution is recursive! For sensible output, this implementation assumes that shorts are no more than 16 bits wide:(See listing 5, overpage)</p>
<!-- Page 18 -->

<table class="sidebartable"><tr><td>

<pre class="programlisting"><code>ostream &amp;expand::operator()(ostream &amp;out) const
{
    if(value &lt; 0)
    {
        out &lt;&lt; &quot;minus &quot; &lt;&lt; expand(-value);
    }
    else if(value &gt;= 1000)
    {
        out &lt;&lt; expand(value / 1000) &lt;&lt; &quot; thousand&quot;;

        if(value % 1000)
        {
            if(value % 1000 &lt; 100)
            {
                out &lt;&lt; &quot; and&quot;;
            }
            out &lt;&lt; &quot; &quot; &lt;&lt; expand(value % 1000);
        }
    }
    else if(value &gt;= 100)
    {
        out &lt;&lt; expand(value / 100) &lt;&lt; &quot; hundred&quot;;

        if( value % 100 )
        {
            out &lt;&lt; &quot; and &quot; &lt;&lt; expand (value % 100);
        }
    }
    else if(value &gt;= 20)
    {
        out &lt;&lt; tens[value / 10];

        if(value % 10)
        {
            out &lt;&lt; &quot; &quot; &lt;&lt; expand(value % 10);
        }
    }
    else
    {
        out &lt;&lt; units_and_teens[value];
    }

    return out; // MM: not in original code
}</code></pre>
</td></tr><tr><td class="title">
Listing 5
</td></tr></table>

<h2>Improvements</h2>
<p>There are a number of obvious improvements and extensions that may be made, but have not been included for obvious reasons:</p>
<ul>
<li><p>increase the domain from short to long, keeping in mind that a 64 bit implementation will probably benefit from a more general table driven approach;</p></li>
<li><p>offer expansion for floating point numbers, using either an internal pointer to a separate object (emulating a â€™virtual constructorâ€™) or a discriminated union to determine correct output method for integers and floating point numbers;</p></li>
<li><p>locale dependency, remembering that not all languages follow the same approach to naming numbers as English: in French, for example, seventy-one is literally â€™sixtyelevenâ€™;</p></li>
<li><p>create an input stream manipulator, contract, that reads in text to yield a number.</p></li>
</ul>
<p>Kevlin Henney</p>
<p>kevlin@wslint.demon.co.uk</p>
</p>
<p><strong>Notes:</strong>&nbsp;Generated via JPG, Google OCR, pandoc markdown from scanned journal</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
