title: Why multiple EOF enters to end program?
body: <p>Trying to understand the behavior of my code. I'm expecting Ctrl-D to lead to the program printing the array and exiting, however it takes 3 presses, and it enters the while loop after the second press.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  void unyon(int p, int q);
  int connected(int p, int q);
  
  int main(int argc, char *argv[]) {
      int c, p, q, i, size, *ptr;
  
      scanf("%d", &amp;size);
  
      ptr = malloc(size * sizeof(int));
  
      while((c = getchar()) != EOF){
          scanf("%d", &amp;p);
          scanf("%d", &amp;q);
  
          printf("p = %d, q = %d\n", p, q);
      }
  
      for(i = 0; i &lt; size; ++i)
          printf("%d\n", *ptr + i);
  
      free(ptr);
      return 0;
  }
  </code></pre>
  
  <p>I read the post here, but I don't quite understand it.
  <a href="https://stackoverflow.com/questions/19889296/how-to-end-scanf-by-entering-only-one-eof">How to end scanf by entering only one EOF</a></p>
  
  <p>After reading that, I'm expecting the first Ctrl-D to clear the buffer, and then I'm expecting c = getchar() to pick up the second Ctrl-D and jump out. Instead the second Ctrl-D enters the loop and prints p and q, and it takes a third Ctrl-D to drop out.</p>
  
  <p>This is made more confusing by the fact that the code below drops out on the first Ctrl-D-</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  main() {
  
      int c, nl;
  
      nl = 0;
      while((c = getchar()) != EOF)
          if (c == '\n')
              ++nl;
      printf("%d\n", nl);
  }
  </code></pre>