title: Using stringstream instead of `sscanf` to parse a fixed-format string
body: <p>I would like to use the facilities provided by <code>stringstream</code> to extract values from a fixed-format <code>string</code> as a type-safe alternative to <code>sscanf</code>.  How can I do this?</p>
  
  <p>Consider the following specific use case.  I have a <code>std::string</code> in the following fixed format:</p>
  
  <p><code>YYYYMMDDHHMMSSmmm</code></p>
  
  <p>Where:</p>
  
  <pre><code>YYYY = 4 digits representing the year
  MM = 2 digits representing the month ('0' padded to 2 characters)
  DD = 2 digits representing the day ('0' padded to 2 characters)
  HH = 2 digits representing the hour ('0' padded to 2 characters)
  MM = 2 digits representing the minute ('0' padded to 2 characters)
  SS = 2 digits representing the second ('0' padded to 2 characters)
  mmm = 3 digits representing the milliseconds ('0' padded to 3 characters)
  </code></pre>
  
  <p>Previously I was doing something along these lines:</p>
  
  <pre><code>string s = "20101220110651184";
  unsigned year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0, milli = 0;    
  sscanf(s.c_str(), "%4u%2u%2u%2u%2u%2u%3u", &amp;year, &amp;month, &amp;day, &amp;hour, &amp;minute, &amp;second, &amp;milli );
  </code></pre>
  
  <p>The width values are magic numbers, and that's ok.  I'd like to use streams to extract these values and convert them to <code>unsigned</code>s in the interest of type safety.  But when I try this:</p>
  
  <pre><code>stringstream ss;
  ss &lt;&lt; "20101220110651184";
  ss &gt;&gt; setw(4) &gt;&gt; year;
  </code></pre>
  
  <p><code>year</code> retains the value <code>0</code>.  It should be <code>2010</code>.</p>
  
  <p>How do I do what I'm trying to do?  I can't use Boost or any other 3rd party library, nor can I use C++0x.</p>