title: How do scanf and getchar work in C?
body: <p>Here is something that confused me.</p>
  
  <pre><code># include &lt;stdio.h&gt;
  # include &lt;limits.h&gt;
  
  int main()
  { 
      int a;
      int b;
  
      printf("Enter two integers: ");
  
  
      while(scanf("%d %d", &amp;a, &amp;b)!=2||b==0||a+b&gt;INT_MAX||a*b&gt;INT_MAX){
  
          printf("Invalid entry, please re-enter: ");
          while(getchar()=='\n'); 
      }
  
      printf("sum is %d, difference is %d, product is %lf, divid is %.2f, remainder is %d", a+b, a-b, (double)a*b, (float)a/b, a%b);
  
      return 0;
  }
  </code></pre>
  
  <p>With above code, if I enter "a 1" press ENTER:</p>
  
  <blockquote>
    <p>Invalid entry, please re-enter:  </p>
  </blockquote>
  
  <p>pops up, then I enter "2 B" press ENTER, the last <code>printf</code> will execute.</p>
  
  <p>However, if I change <code>while(getchar()=='\n');</code> to <code>while(getchar()!='\n');</code>, and with the same entry (I enter "a 1" press ENTER)</p>
  
  <blockquote>
    <p>Invalid entry, please re-enter: </p>
  </blockquote>
  
  <p>pops up, then I enter "2 B" press ENTER), the last <code>printf</code> will not execute, and</p>
  
  <blockquote>
    <p>Invalid entry, please re-enter: </p>
  </blockquote>
  
  <p>pops up again.</p>
  
  <p>What causes the difference here? How exactly do <code>scanf</code> and <code>getchar</code> work?</p>