title: Flush input in C
body: <p>I'm a student in software engineering and I'm on Christmas break in order to get better for the next semester I've been writing various console applications to practice. I have however ran into a problem, I need to get integer input from the user. I've been using <code>fgets</code> to get the string from <code>stdin</code> and then using <code>sscanf</code> to get the integer (Which has worked fine) but if the user enters more than my buffer size trailing characters are left in the stream (Including a newline with skips my next call to <code>fgets</code>). I've looked around and found that most people seem to suggest <code>while(getchar() != '\n');</code> that however causes me a problem because if there isn't a newline character to be consumed an unnecessary scan for input takes place.</p>
  
  <p><strong>Example:</strong></p>
  
  <pre><code>int ch;
  char* buffer = (char*)malloc(BUFSIZ*sizeof(char));
  while((ch = getchar()) != '\n' &amp;&amp; ch != EOF);
  fgets(buffer,BUFSIZ*sizeof(char),stdin);
  </code></pre>
  
  <p>If the buffer isn't too small and no trailing characters remain in the stream then there is an unecessary <code>getchar()</code> causing input.</p>
  
  <p><strong>Output:</strong></p>
  
  <pre><code>A
  
  A
  
  You typed A
  
  Intended Output:
  
  A
  
  You typed A
  </code></pre>
  
  <p>I hope that I made this clear enough, I appreciate any help.</p>