Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To properly handle errors, I'd suggest</p> <pre><code>int age; bool error = false; do { cout &lt;&lt; "Please enter your age\n"; error = true; if (!(cin &gt;&gt; age)) { cout &lt;&lt; "Invalid input\n"; cin.clear(); // skip rest of line to avoid numerous spurious errors on // non-numerical input: cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); if (!cin.good()) break; } else if (age &gt; 105) { cout &lt;&lt; "You're Too Old\n"; } else if (age &lt; 1) { cout &lt;&lt; "You haven't been born yet!\n"; } else { error = false; } } while (error); </code></pre> <p>Note</p> <ul> <li>This also treats stream errors (e.g. bad input like <code>whoops</code>)</li> <li>it <em>actually</em> reads the input again, if there was an error</li> </ul> <p>See it <strong><a href="http://coliru.stacked-crooked.com/view?id=3459955bd2905b73201e6528ca468ac2-46908b44a13fd97d96dc5f34139b69aa" rel="nofollow">live on Coliru</a></strong> with the following input:</p> <pre><code>332 -9 0 whoops flargle blasted furnace 22 </code></pre> <p>Printing:</p> <blockquote> <p><code>Please enter your age</code> <strong>332</strong> <br/><code>You're Too Old</code> <br/><code>Please enter your age</code> <strong>-9</strong> <br/><code>You haven't been born yet!</code> <br/><code>Please enter your age</code> <strong>0</strong> <br/><code>You haven't been born yet!</code> <br/><code>Please enter your age</code> <strong>whoops</strong> <br/><code>Invalid input</code> <br/><code>Please enter your age</code> <strong>flargle blasted furnace</strong> <br/><code>Invalid input</code> <br/><code>Please enter your age</code> <strong>22</strong> <br/><code>Your age is: 22</code></p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload