title: How to clear input buffer in C?
body: <p>I have the following program:</p>
  
  <pre><code>int main(int argc, char *argv[])
  {
    char ch1, ch2;
    printf("Input the first character:"); // Line 1
    scanf("%c", &amp;ch1); 
    printf("Input the second character:"); // Line 2
    ch2 = getchar();
  
    printf("ch1=%c, ASCII code = %d\n", ch1, ch1);
    printf("ch2=%c, ASCII code = %d\n", ch2, ch2);
  
    system("PAUSE");  
    return 0;
  }
  </code></pre>
  
  <p>As the author of the above code have explained:
  The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: <code>Enter key (ASCII code 13)</code> and <code>\n (ASCII code 10)</code>. Therefore, at Line 2, it will read the <code>\n</code> and will not wait for the user to enter a character.</p>
  
  <p>OK, I got this. But my first question is: Why the second <code>getchar()</code> (<code>ch2 = getchar();</code>) does not read the <code>Enter key (13)</code>, rather than <code>\n</code> character?</p>
  
  <p>Next, the author proposed 2 ways to solve such probrems:</p>
  
  <ol>
  <li><p>use <code>fflush()</code></p></li>
  <li><p>write a function like this:</p>
  
  <pre><code>void
  clear (void)
  {    
    while ( getchar() != '\n' );
  }
  </code></pre></li>
  </ol>
  
  <p>This code worked actually. But I cannot explain myself how it works? Because in the while statement, we use <code>getchar() != '\n'</code>, that means read any single character except <code>'\n'</code>? if so, in the input buffer still remains the <code>'\n'</code> character?</p>