If I try something such as:
int anint;
char achar;
printf("\nEnter any integer:");
scanf("%d", &anint);
printf("\nEnter any character:");
scanf("%c", &achar);
printf("\nHello\n");
printf("\nThe integer entered is %d\n", anint);
printf("\nThe char entered is %c\n", achar);
It allows entering an integer, then skips the second scanf completely, this is really strange, as when I swap the two (the char scanf first), it works fine. What on earth could be wrong?
When reading input using
scanf, the input is read after the return key is pressed but the newline generated by the return key is not consumed byscanf, which means the next time you read acharfrom standard input there will be a newline ready to be read.One way to avoid is to use
fgetsto read the input as a string and then extract what you want usingsscanfas:Another way to consume the newline would be to
scanf("%c%*c",&anint);. The%*cwill read the newline from the buffer and discard it.You might want to read this:
C FAQ : Why does everyone say not to use scanf?