The program below prompts the user to input something. If the input is acceptable to fgets
, the program will print what the user had input. The program works, except that something strange happens when the user presses Ctrld at the prompt. When the user presses Ctrld at the prompt, the program enters an infinite loop where the prompt gets printed over and over again. Why does this happen?
#include <stdio.h>
#define BUFSIZE 512
int main(void)
{
char input_buf[BUFSIZE];
char *user_input;
while (1) {
user_input = NULL;
printf("Input: "); /* Prompt. */
if ((user_input = fgets(input_buf, BUFSIZE, stdin)) == NULL) {
printf("Invalid input. Try again.\n");
continue;
} else {
printf("User input: %s", user_input);
break;
}
}
return 0;
}