title: Equivalent of %05d with std::stringstream for negative numbers?
body: <p>I'm trying to create a replacement for sprintfs' %05d behavior. Althought, I've found a similar question <a href="https://stackoverflow.com/questions/2839592/equivalent-of-02d-with-stdstringstream">here on stackoverflow</a>, the proposed solution there doesn't work for me when I'm testing with negative numbers.</p>
  
  <p>Doing a "sprintf(buf, "%05d", -12)", I'm getting "-0012" back which looks nice.</p>
  
  <p>Using stringstream, width and fill, I'm getting "00-12" which seams reasonable when looking at the docs from <a href="http://www.cplusplus.com/reference/ios/basic_ios/fill/" rel="nofollow noreferrer">std::basic_ios::fill</a></p>
  
  <blockquote>
    <p>The fill character is the character used by output insertion functions to fill spaces when padding results to the field width.</p>
  </blockquote>
  
  <p>but doesn't look like something one could wish.</p>
  
  <p>So I'm confused and don't know if I'm doing something obvious wrong or if width/fill from the std streams doesn't easily support this situation.</p>
  
  <p>A compilable <a href="http://codepad.org/6djfpLAH" rel="nofollow noreferrer">testcode can be found on codepad</a>.
  Here's an extract of the stream based conversion:</p>
  
  <pre><code>std::string NumberToString(const long iVal, const int iNumDigit)
  {
      std::stringstream ss;
  
      if      (iNumDigit &gt;= 0) ss.fill(' ');
      else if (iNumDigit &lt; 0)  ss.fill('0');
      ss.width(std::abs(iNumDigit));
  
      ss &lt;&lt; iVal;
  
      return ss.str();
  }
  </code></pre>
  
  <p>EDIT1: Solution:</p>
  
  <p>To match the std stream approach with printf formatting for %05d, jrok's solution can be used for the case with leading zeros. Here's the new function:</p>
  
  <pre><code>std::string NumberToString(const long iVal, const int iNumDigit)
  {
      std::stringstream ss;
  
      if      (iNumDigit &gt;= 0) ss.fill(' ');
      else if (iNumDigit &lt; 0)  { ss.fill('0'); ss.setf(std::ios::internal, std::ios::adjustfield); }
      ss.width(std::abs(iNumDigit));
  
      ss &lt;&lt; iVal;
  
      return ss.str();
  }
  </code></pre>