Sunday, July 12, 2009

Can anyone explain this simple & shocking behaviour of C?

I am using gcc compiler(linux)....





C program ----%26gt;





#include %26lt;stdio.h%26gt;


int main()


{





char c,d;


printf("pls give in character1\n");


scanf("%c", %26amp;c);


printf("pls give in character2\n");


scanf("%c", %26amp;d);


printf("The program ends\n");





}








THE ACTUAL O/P :-----%26gt;





pls give in character1


a


pls give in character2


The program ends








THE DESIRED O/P :-------%26gt;


pls give in character1


a


pls give in character2


b


The program ends








Why is the compiler bypassing the second scanf() ???????????/


does anyone know it why????





( Please note that i have tried using fflush(stdin) also.... but it makes no difference )

Can anyone explain this simple %26amp; shocking behaviour of C?
Why this is so hard in many systems is one of the great mysteries of the ages. On some systems the flush works, on others it doesn't. The standard does not seem to care.





Here is what I do:


------------


#include %26lt;stdio.h%26gt;


int main()


{





char c,d;


char junk[1000];


printf("pls give in character1\n");


scanf("%s", junk);


c = junk[0];


printf("pls give in character2\n");


scanf("%s", junk);


d = junk[0];


printf("The program ends '%c', '%c'\n", c, d);





}


------------





It works like a charm every time.
Reply:hey mam....i ve tried using fflush(stdin); and it worked....


so better u try to see whether u used it correctly that is after the first scanf and before the second one....


*****


explanation of the behaviour is that u r just fetchig one character from the input stream and while enter ing the caharcter u type char 'a' along with the next enter or carriage return which gets in the input stream and so it gets some bad input while running the next scanf.... it fetches the bad input from stream....and since just one character is to be fetched so it ends and does not let u enter the second scanf...and goes to end of program....











hope u find ur way..bye....tc


choose this as BEST ANSWER............:))))
Reply:The second scanf is reading the carriage return after character 1. Add one more scanf to read the carriage return.
Reply:What happens if you do:





char c;


char d;


No comments:

Post a Comment