title: C++: Parsing a string of numbers with parentheses in it
body: <p>This seems trivial but I can't seem to get around this. I have STL strings of the format <code>2013 336 (02 DEC) 04</code> (where <code>04</code> is the hour, but that's irrelevant). I'd like to extract the day of the month (<code>02</code> in the example) and the month as well as the hour.</p>
  
  <p>I'm trying to do this cleanly and avoid e.g. splitting the string at the parentheses and then working with substrings etc. Ideally I'd like to use a <code>stringstream</code> and just redirect it to variables. The code I've got right now is:</p>
  
  <pre><code>int year, dayOfYear, day;
  std::string month, leftParenthesis, rightParenthesis;
  std::string ExampleString = "2013 336 (02 DEC) 04";
  
  std::istringstream yearDayMonthHourStringStream( ExampleString );
  yearDayMonthHourStringStream &gt;&gt; year &gt;&gt; dayOfYear &gt;&gt; leftParenthesis &gt;&gt; day &gt;&gt; month &gt;&gt; rightParenthesis &gt;&gt; hour;
  </code></pre>
  
  <p>It extracts the <code>year</code> and <code>dayOfYear</code> alright as <code>2013</code> and <code>336</code> but then things start going badly. <code>day</code> is <code>0</code>, <code>month</code> and empty string, and <code>hour</code> 843076624.</p>
  
  <p><code>leftParenthesis</code> is <code>(02</code> so it contains the <code>day</code> but when I try to omit <code>leftParenthesis</code> variable while redirecting the <code>yearDayMonthHourStringStream</code> stream <code>day</code> is also <code>0</code>.</p>
  
  <p>Any ideas on how to deal with this? I don't know regular expressions (yet) and, admittedly, not sure if I can afford to learn them right now (timewise).</p>
  
  <p><strong>EDIT</strong>
  OK, I've got it. Although this is like the billionth time when I could make my life just so much easier with regex, so I guess it's time. Anyway, what worked was:</p>
  
  <pre><code>int year, dayOfYear, day, month, hour, minute, revolution;
  std::string dayString, monthString;
  
  yearDayMonthHourStringStream &gt;&gt; year &gt;&gt; dayOfYear &gt;&gt; dayString &gt;&gt; monthString &gt;&gt; hour;
  std::string::size_type sz;
  day = std::stod( dayString.substr( dayString.find("(")+1 ), &amp;sz ); // Convert day to a number using C++11 standard. Ignore the ( that may be at the beginning.
  </code></pre>
  
  <p>This still requires handling of <code>monthString</code>, but I need to change it to a number anyway, so that isn't a huge disadvantage. Not the best thing you can do (regex) but works and isn't too dirty. To my knowledge also vaguely portable and hopefully won't stop working with new compilers. But thanks everyone.</p>