Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yo can use <code>if(cin)</code> to check the state of the input stream and since operator>> will return the input stream that was passed to it you can use <code>if(cin&gt;&gt;iUserguess)</code></p> <p>If cin is in a failed state -maybe because the user entered a non number- the expression <code>if(cin&gt;&gt;iUserguess)</code> will evaluate to false.</p> <p>If the user enters a non number you will need to call <code>cin.clear()</code> to clear the stream state and <code>cin.ignore()</code> to discard the input, before trying to read a number again.</p> <p>so using your example, it could be changed to this:</p> <pre><code>#include &lt;iostream&gt; #include &lt;ctime&gt; #include &lt;limits&gt; using namespace std; int main() { int iGumballs; int iUserguess; int iGuesses = 0; while (true) { system("CLS"); iGuesses = 0; srand(static_cast&lt;unsigned int&gt;(time(0))); iGumballs = rand()%1000+1; cout &lt;&lt; "How many gumballs are in the bumball jar? You guess! 1-1000" &lt;&lt; endl; do { cout &lt;&lt; "Enter your guess: "; if(cin &gt;&gt; iUserguess) { iGuesses ++; if(iUserguess &gt; iGumballs) { cout &lt;&lt; "Too high!" &lt;&lt; endl &lt;&lt; endl; continue; } if(iUserguess &lt; iGumballs) { cout &lt;&lt; "Too low!" &lt;&lt; endl &lt;&lt; endl; continue; } } else { cout&lt;&lt;"incorrect input - try again\n\n"; cin.clear(); cin.ignore(numeric_limits&lt;streamsize&gt;::max(),'\n'); continue; } } while(iUserguess &gt; iGumballs || iUserguess &lt; iGumballs); cout &lt;&lt; "You guessed the right amout of gumballs" &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; "You took " &lt;&lt; iGuesses &lt;&lt; " guesses" &lt;&lt; endl &lt;&lt; endl; system ("pause"); } return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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