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? 


#include

main(){


char a;


while(1){



scanf("%c",&a);



if(a=='x')

printf("its x");

else

printf("not x");


}







}

Post a Reply

Replies

Oldest  Newest  Rating
0 c student · November 15, 2015
try this
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1052863818&id=1043284351
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!
+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 Ishfaq Zaman · November 10, 2015
Wow it works thanks.

Could you tell me what this syntax is called?
0 c student · November 9, 2015
scanf ("%c%*c", &a);
  • 1

C

107,042 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator