Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to print a bunch of integers with the same formatting?
    primarykey
    data
    text
    <p>I would like to print a bunch of integers on 2 fields with <code>'0'</code> as fill character. I can do it but it leads to code duplication. How should I change the code so that the code duplication can be factored out?</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;ctime&gt; #include &lt;sstream&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; using namespace std; string timestamp() { time_t now = time(0); tm t = *localtime(&amp;now); ostringstream ss; t.tm_mday = 9; // cheat a little to test it t.tm_hour = 8; ss &lt;&lt; (t.tm_year+1900) &lt;&lt; setw(2) &lt;&lt; setfill('0') &lt;&lt; (t.tm_mon+1) // Code duplication &lt;&lt; setw(2) &lt;&lt; setfill('0') &lt;&lt; t.tm_mday &lt;&lt; setw(2) &lt;&lt; setfill('0') &lt;&lt; t.tm_hour &lt;&lt; setw(2) &lt;&lt; setfill('0') &lt;&lt; t.tm_min &lt;&lt; setw(2) &lt;&lt; setfill('0') &lt;&lt; t.tm_sec; return ss.str(); } int main() { cout &lt;&lt; timestamp() &lt;&lt; endl; return 0; } </code></pre> <p>I have tried</p> <pre class="lang-cpp prettyprint-override"><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; s, int i) { return s &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; i; } </code></pre> <p>but it did not work, the <code>operator&lt;&lt;</code> calls are ambigous.</p> <hr> <p><strong>EDIT</strong> I got 4 awesome answers and I picked the one that is perhaps the simplest and the most generic one (that is, doesn't assume that we are dealing with timestamps). For the actual problem, I will probably use <a href="http://en.cppreference.com/w/cpp/io/manip/put_time" rel="nofollow"><code>std::put_time</code></a> or <a href="http://linux.die.net/man/3/strftime" rel="nofollow"><code>strftime</code></a> though.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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