While loop acting strange when scaning characters

+1 Ishfaq Zaman · November 9, 2015

Here's a really simple code:

Every time I run it the loop is executing twice and it's only taking the char input once.Anyone know how to fix this? 



char a;




printf("its x");


printf("not x");



Post a Reply


Oldest  Newest  Rating
+2 c student · November 10, 2015
@neeraj polas

fflush has undefined behavior with stdin.

@Ishfaq Zaman

the reason why your scanf runs twice and seems to only take one input is because when you type in a character and press the enter key, your scanf takes the character on the first run and then it will take in your enter key on the second.  what the %*c does is it scans and suppresses your enter key.
0 neeraj polas · November 10, 2015
Use "fflush(stdin);"  before scanf or after if condition.
0 c student · November 9, 2015
scanf ("%c%*c", &a);
0 Ishfaq Zaman · November 10, 2015
Wow it works thanks.

Could you tell me what this syntax is called?
0 neeraj polas · November 14, 2015
@c student
undefined behavior ? like what?
fflush(stdin) just clears the scanf buffer rt?
I would like to know the actual reason or how fflush works?.............bcoz when i searched online I had this" The answer to this is that fflush(stream) is only formally defined for output streams, so fflush(stdout) is OK, but fflush(stdin) is not".
Well see I am good in C but not that great in C .........still a learner!:) I just know many functions as what they do .....want to know the back end story!
0 c student · November 15, 2015
try this
  • 1



One of the most popular languages of all time.

Bucky Roberts Administrator