title: How to check if the input is a valid integer without any other chars?
body: <pre><code>#include &lt;iostream&gt;
  #include &lt;limits&gt;
  
  using namespace std;
  
  int main()
  {
      int x;
      cout &lt;&lt; "5 + 4 = ";
      while(!(cin &gt;&gt; x)){
          cout &lt;&lt; "Error, please try again." &lt;&lt; endl;
          cin.clear();
          cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\n');
      }
      if (x == (5 + 4)){
          cout &lt;&lt; "Correct!" &lt;&lt; endl;
      }
      else{
          cout &lt;&lt; "Wrong!" &lt;&lt; endl;
      }
      return 0;
  }
  </code></pre>
  
  <p>How can I check if the user inputs a valid integer? In this program I wrote above, if the user inputs <code>9</code>, it should be correct, however, if the user inputs <code>9a</code> for example, it should return an error, but it doesn't for some reason. How can I correct it?</p>
  
  <p>How I did it using cin.peek()</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;limits&gt;
  #include &lt;stdio.h&gt;
  
  using namespace std;
  
  int main()
  {
      int x;
      bool ok;
      cout &lt;&lt; "5 + 4 = ";
  
      cin &gt;&gt; x;
  
      while(!ok){
    cin &gt;&gt; x;
  
    if(!cin.fail() &amp;&amp; (cin.peek() == EOF || cin.peek() == '\n')){
    ok = true;
    }
    else{
    cout &lt;&lt; "Error, please try again." &lt;&lt; endl;
    cin.clear();
    cin.ignore(numeric_limits&lt;streamsize&gt;::max(), '\n');
    }
      }
  
      if (x == (5 + 4)){
    cout &lt;&lt; "Correct!" &lt;&lt; endl;
      }
      else{
    cout &lt;&lt; "Wrong!" &lt;&lt; endl;
      }
  
      return 0;
  }
  </code></pre>