title: Resetting the State of a Stream
body: <p>I have a question which is slightly similar to this question on stackoverflow <a href="https://stackoverflow.com/questions/4960399/stdcin-clear-fails-to-restore-input-stream-in-a-good-state">std::cin.clear() fails to restore input stream in a good state</a>, but the answer provided there does not work for me.</p>
  
  <p>The question is: how can I reset the state of a stream to 'good' again?</p>
  
  <p>Here is my code how I try it, but the state is never set to good again. I used both of the lines ignore separately.</p>
  
  <pre><code>int _tmain(int argc, _TCHAR* argv[])
  {
      int result;
      while ( std::cin.good() )
      {
          std::cout &lt;&lt; "Choose a number: ";
          std::cin &gt;&gt; result;
  
          // Check if input is valid
          if (std::cin.bad())
          {
              throw std::runtime_error("IO stream corrupted");
          }
          else if (std::cin.fail())
          {
              std::cerr &lt;&lt; "Invalid input: input must be a number." &lt;&lt; std::endl;
              std::cin.clear(std::istream::failbit);
              std::cin.ignore();
              std::cin.ignore(INT_MAX,'\n');
              continue;
          }
          else
          {
              std::cout &lt;&lt; "You input the number: " &lt;&lt; result &lt;&lt; std::endl;
          }
      }
      return 0;
  }
  </code></pre>