title: How to test whether stringstream operator>> has parsed a bad type and skip it
body: <p>I am interested in discussing methods for using <code>stringstream</code> to parse a line with multiple types. I would begin by looking at the following line:</p>
  
  <pre><code>"2.832 1.3067 nana 1.678"
  </code></pre>
  
  <p>Now lets assume I have a long line that has multiple <code>strings</code> and <code>doubles</code>. The obvious way to solve this is to tokenize the string and then check converting each one. I am interested in skipping this second step and using <code>stringstream</code> directly to only find the numbers. </p>
  
  <p>I figured a good way to approach this would be to read through the string and check if the <code>failbit</code> has been set, which it will if I try to parse a string into a double. </p>
  
  <p>Say I have the following code:</p>
  
  <pre><code>string a("2.832 1.3067 nana 1.678");
  
   stringstream parser;
   parser.str(a);
  
   for (int i = 0; i &lt; 4; ++i)
   {
       double b;
       parser &gt;&gt; b;
       if (parser.fail())
       {
           std::cout &lt;&lt; "Failed!" &lt;&lt; std::endl;
           parser.clear();
       }
       std::cout &lt;&lt; b &lt;&lt; std::endl;
   }
  </code></pre>
  
  <p>It will print out the following: </p>
  
  <pre><code>2.832
  1.3067
  Failed!
  0
  Failed!
  0
  </code></pre>
  
  <p>I am not surprised that it fails to parse a string, but <strong>what is happening internally such that it fails to clear its <code>failbit</code> and parse the next number?</strong></p>