title: Why do I get an infinite loop if I enter a letter rather than a number?
body: <p>I am writing this code for a homework assignment (just starting C++ so please go easy). We've just started while, do-while, and for loops today. The program runs fine except that if you enter a letter when the program asks for an integer, it loops infinitely. What is going on? (Code below)
  ***EDIT: To clarify, the part that is looping is: "The number you have entered is negative. Please enter a positive number to continue." But the user is not given a chance to enter another number. It just keeps printing this.</p>
  
  <pre><code>    #include &lt;iostream&gt;
  using namespace std;
  
  int main ( )
  {
      //define variables
      int num1, num2, total;
      char answer1;
  
      do
      {
          //user enters a number
          cout &lt;&lt; "\nPlease enter a positive number and press Enter: \n";
          cin &gt;&gt; num1;
  
          //check that the given num1 value is positive
          while (num1 &lt; 0)
          {
              cout &lt;&lt; "The number you entered is negative.\nPlease enter a positive number to continue.\n";
              cin &gt;&gt; num1;
          }
  
          cout &lt;&lt; endl;
  
          //add the sum of 1 through num1 value
          num2 = 1;
          total = 0;
          while (num1 &gt;= num2)
          {
              total = total + num2;
              num2 ++;
          }
  
          //tell the user the sum
          cout &lt;&lt; "The total of all the integers\nfrom 1 to " &lt;&lt; num1 &lt;&lt; " is: \n";
          cout &lt;&lt; total;
  
          //ask if the user wants to try again
          cout &lt;&lt; "\n\nWould you like to try again with a new number?\nEnter y for yes or n for no.\n";
          cin &gt;&gt; answer1;
      } while (answer1 == 'y');   
  
      cout &lt;&lt; endl;
      return 0;
  }
  </code></pre>