title: c++ stringstream is too slow, how to speed up?
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/5678932/fastest-way-to-read-numerical-values-from-text-file-in-c-double-in-this-case">Fastest way to read numerical values from text file in C++ (double in this case)</a>  </p>
  </blockquote>
  
  
  
  <pre><code>#include &lt;ctime&gt;
  #include &lt;cstdlib&gt;
  #include &lt;string&gt;
  #include &lt;sstream&gt;
  #include &lt;iostream&gt;
  #include &lt;limits&gt;
  
  using namespace std;
  
  static const double NAN_D = numeric_limits&lt;double&gt;::quiet_NaN();
  
  void die(const char *msg, const char *info)
  {
      cerr &lt;&lt; "** error: " &lt;&lt; msg &lt;&lt; " \"" &lt;&lt; info &lt;&lt; '\"';
      exit(1);
  }
  
  double str2dou1(const string &amp;str)
  {
      if (str.empty() || str[0]=='?') return NAN_D;
      const char *c_str = str.c_str();
      char *err;
      double x = strtod(c_str, &amp;err);
      if (*err != 0) die("unrecognized numeric data", c_str);
      return x;
  }
  
  static istringstream string_to_type_stream;
  
  double str2dou2(const string &amp;str)
  {
      if (str.empty() || str[0]=='?') return NAN_D;
      string_to_type_stream.clear();
      string_to_type_stream.str(str);
      double x = 0.0;
      if ((string_to_type_stream &gt;&gt; x).fail())
          die("unrecognized numeric data", str.c_str());
      return x;
  }
  
  int main()
  {
      string str("12345.6789");
  
      clock_t tStart, tEnd;
  
      cout &lt;&lt; "strtod: ";
      tStart=clock();
  
      for (int i=0; i&lt;1000000; ++i)
          double x = str2dou1(str);
  
      tEnd=clock();
      cout &lt;&lt; tEnd-tStart &lt;&lt; endl;
  
      cout &lt;&lt; "sstream: ";
      tStart=clock();
  
      for (int i=0; i&lt;1000000; ++i)
          double x = str2dou2(str);
  
      tEnd=clock();
      cout &lt;&lt; tEnd-tStart &lt;&lt; endl;
  
      return 0;
  }
  </code></pre>
  
  <p>strtod: 405<br>
  sstream: 1389</p>
  
  <p>update: remove undersocres, env: win7+vc10</p>