This may be a simple question, but i searched a lot and still didn't figure it out. I compiles below snip code by gcc and run program from terminal. In correct, It allow to enter an int and a char but it doesn't. It doesn't wait to enter the char??
Anyone here can help me will be kind. thanks in advance!
#include <stdio.h>
int main()
{
char c;
int i;
// a
printf("i: ");
fflush(stdin); scanf("%d", &i);
// b
printf("c: ");
fflush(stdin); scanf("%c", &c);
return 0;
}
%d
will read consecutive digits until it encounters a non-digit. %c
reads one character. Probably what's happening is that you're giving it a number (several digits) followed by a new line. %c
then reads in that new line. You were probably intending for the fflush(stdin);
to discard anything that hadn't yet been read, but unfortunately, that's undefined behavior.
The solution is to discard all whitespace before reading the character:
scanf(" %c", &c);
Note the space at the start. That means to discard all whitespace.
You can use the getchar()
to achieve what you want.
or consume the extra newline by using:-
scanf(" %c", &c);
^^^ <------------Note the space
Reason:- Your next scanf for reading the character just reads/consumes the newline and hence never waits for user input
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With