C++ Example : Not able to understand what is being done?
<p>I found this link at <a href="http://www.parashift.com/c++-faq-lite/istream-and-ignore.html" rel="nofollow">http://www.parashift.com/c++-faq-lite/istream-and-ignore.html</a></p>

<p>which shows "How can I get std::cin to skip invalid input characters?"</p>

<pre><code>Use std::cin.clear() and std::cin.ignore().

#include &lt;iostream&gt;
#include &lt;limits&gt;

int main()
{
  int age = 0;

  while ((std::cout &lt;&lt; "How old are you? ")
         &amp;&amp; !(std::cin &gt;&gt; age)) {
    std::cout &lt;&lt; "That's not a number; ";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n');
  }

  std::cout &lt;&lt; "You are " &lt;&lt; age &lt;&lt; " years old\n";
  ...
}
Of course you can also print the error message when the input is out of range. For example, if you wanted the age to be between 1 and 200, you could change the while loop to:
  ...
  while ((std::cout &lt;&lt; "How old are you? ")
         &amp;&amp; (!(std::cin &gt;&gt; age) || age &lt; 1 || age &gt; 200)) {
    std::cout &lt;&lt; "That's not a number between 1 and 200; ";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n');
  }
  ...
Here's a sample run:
How old are you? foo
That's not a number between 1 and 200; How old are you? bar
That's not a number between 1 and 200; How old are you? -3
That's not a number between 1 and 200; How old are you? 0
That's not a number between 1 and 200; How old are you? 201
That's not a number between 1 and 200; How old are you? 2
You are 2 years old
</code></pre>

<p>I am not able to get how it is doing it > Can any one explain please?</p>

<p>I have doubts with :</p>

<pre><code>while ((std::cout &lt;&lt; "How old are you? ")
             &amp;&amp; !(std::cin &gt;&gt; age)) 
</code></pre>

<p>How is it checking the valid entry? I mean to ask do expressions "std::cout &lt;&lt; "How old are you?" and "!(std::cin >> age)" , return true or false which are being ANDed ?</p>

<p>another thing which is confusing is the usage,</p>

<pre><code>std::cin.clear();
std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n');
</code></pre>

<p>What are there purpose ? Searched on google about these functions but still I am not clear.
Particularly, <code>std::numeric_limits&lt;std::streamsize&gt;::max()</code></p>

<p>Can any one help?
Thanks</p>
