When I use fgets in the following piece of code without the newline character in printf , the program does not wait for my input. It seems like either using a new line character in the printf statement before OR using the flushing the stdin fixes the problem. But can someone expain what's going on and why a \n or flsuhing fixes it?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *userInput = malloc(sizeof(*userInput) * 2);
printf("Enter a character:"); // This leads to an issue where fgets does not wait for an input
/*
Using either of the below statements fixes it though
printf("Enter a character:\n");
OR
fflush
*/
fgets(userInput, 2, stdin);
printf("The character you entered is: %c \n", userInput[0]);
}
Thanks!