Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When confronted with this in the past, I've used a <code>stringstream</code> along with a manipulator that displays the current contents of the <code>stringstream</code> using <code>MessageBox</code>:</p> <pre><code>#include &lt;windows.h&gt; #include &lt;sstream&gt; #include &lt;ostream&gt; std::ostream &amp;MessageBox(std::ostream &amp;s) { std::ostringstream *st = dynamic_cast&lt;std::ostringstream *&gt;(&amp;s); if (NULL != st) ::MessageBox(NULL, st-&gt;str().c_str(), "", MB_OK); return s; } </code></pre> <p>To use this, the syntax looks a fair amount like using <code>cout</code>, but with <code>MessageBox</code> replacing <code>std::endl</code>. For example:</p> <pre><code>std::ostringstream stm; stm &lt;&lt; " blah blah blah. Value: " &lt;&lt; 1213.1231 &lt;&lt; MessageBox; </code></pre> <p>Edit: mostly for fnieto. In this case, the downcast really <em>is</em> necessary. The reason is fairly simple: a typical inserter receives and returns a reference to an ostream:</p> <pre><code>std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, T const &amp;t) { // code here to insert t into os, then return os; } </code></pre> <p>This takes the original stringstream object and silently (and safely) casts it up to a simple ostream. That's fine in itself, and works fine for most inserters and manipulators, because they only interact with the <code>ostream</code> interface themselves.</p> <p>This manipulator, however, is a bit different -- it uses the <code>str()</code> member, which <code>ostream</code> doesn't define at all. For our call to <code>str()</code> to resolve and compile, we have to convert the <code>ostream &amp;</code> to an <code>ostringstream &amp;</code>, so the compiler is aware that the object we're working with really will have a <code>str()</code> member. </p> <p>To eliminate the downcast, we'd really only have one choice: make its parameter an <code>ostringstream &amp;</code>. That would work as long as we never chained operators:</p> <pre><code>my_stream &lt;&lt; x; my_stream &lt;&lt; MessageBox; </code></pre> <p>but trying to chain those would fail:</p> <pre><code>// should be equivalent: my_stream &lt;&lt; x &lt;&lt; MessageBox; </code></pre> <p>Worse, the compiler's error message will probably try to tell the user something about <code>std::basic_ostream&lt;char&gt;::str()</code>, which isn't mentioned in the user's code at all. Worse still, most people are sufficiently accustomed to chaining or not giving identical results that it would probably take them a while to even figure out why the code sometimes worked fine, and other times failed to compile, with a completely indecipherable error message.</p>
 

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