title: How to check for a valid user input in C++
body: <p>I'm trying to build the Bulls &amp; Cows game in C++.  I've implemented most of the logic.  The game runs continuously with the use of an infinite loop and generates a random value at each run.</p>
  
  <p>What I'm trying to do now is to now is to take the user input and run the code if the input is valid (can ONLY be a 4 digit integer).  This is my implementation:</p>
  
  <pre><code>#include ...
  
  using namespace std;
  
  vector&lt;int&gt; getDigits(int modelValue) {
      vector&lt;int&gt; vectorValue;
      int extractedDigit = 0;
      int modulant = 10000;
      int divisor = 1000;
  
      for (int i = 0; i &lt; 4; i++) {
          extractedDigit = (modelValue % modulant) / divisor;
          vectorValue.push_back(extractedDigit);
          modulant /= 10;
          divisor /= 10;
      }return vectorValue;
  }
  
  
  int main() {
      for (;;) {
          int model = rand() % 9000 + 1000;
          int guess = 0000;
          int bulls = 0;
          int cows = 0;
          int counter = 1;
  
          cout &lt;&lt; "This is the random 4-digit integer: " &lt;&lt; model &lt;&lt; endl;
          cout &lt;&lt; "Enter a value to guess: ";
          cin &gt;&gt; guess;
  
          if ((guess &gt;= 1000) &amp;&amp; (guess &lt;= 9999) &amp;&amp; (cin)) {
  
              vector&lt;int&gt; modelVector = getDigits(model);
              vector&lt;int&gt; guessVector = getDigits(guess);
  
              for (int i = 0; i &lt; 4; i++) {
  
                  if (find(modelVector.begin(), modelVector.end(), guessVector[i]) != modelVector.end()) {
                      if (modelVector[i] == guessVector[i]) { bulls += 1; }
                      else { cows += 1; }
                  }
              }cout &lt;&lt; "There are " &lt;&lt; bulls &lt;&lt; " bulls and " &lt;&lt; cows &lt;&lt; " cows" &lt;&lt; endl;
          }
          else {
              cout &lt;&lt; "Please enter a valid 4-digit integer between 0000 and 9999" &lt;&lt; endl;
              cin.clear();
          }
      }return 0;
  }
  </code></pre>
  
  <p>But when I run and input something invalid, what I get is a continuously running <a href="https://i.stack.imgur.com/HM4ou.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HM4ou.png" alt="console"></a>.</p>