title: Why does the use of fgets result in an infinite loop when Ctrl-d is pressed?
body: <p>The program below prompts the user to input something. If the input is acceptable to <code>fgets</code>, the program will print what the user had input. The program works, except that something strange happens when the user presses <kbd>Ctrl</kbd><kbd>d</kbd> at the prompt. When the user presses <kbd>Ctrl</kbd><kbd>d</kbd> at the prompt, the program enters an infinite loop where the prompt gets printed over and over again. Why does this happen?</p>
  <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;
  #define BUFSIZE 512
  
  int main(void)
  {
      char input_buf[BUFSIZE];
      char *user_input;
      while (1) {
          user_input = NULL;
          printf(&quot;Input: &quot;);  /* Prompt. */
          if ((user_input = fgets(input_buf, BUFSIZE, stdin)) == NULL) {
              printf(&quot;Invalid input. Try again.\n&quot;);
              continue;
          } else {
              printf(&quot;User input: %s&quot;, user_input);
              break;
          }
      }
      return 0;
  }
  </code></pre>