Tuesday, July 14, 2009

Why doesn't this C function work more than once?

CONTINUE (void) {


char cont=1;


printf("\n(Press c, then return to continue.)");


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


if (cont == 99) {


printf("\n...");


return 0;


}


else {


printf("\nInvalid input");


return 1;


}


}

Why doesn't this C function work more than once?
This is an annoying problem with Scanf. It cashes the value and hence why your not prompted. You need to clear the Scanf cache but I cant remember how to do that.





I think one way of clearing the cache automatically is to allow a space between arguments in a scanf function. For example :





printf("\n(Press c, then return to continue.)");


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





and not





printf("\n(Press c, then return to continue.)");


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








Notice the space between the " and % in the scanf function. Give that ago and see if it fixes the problem.
Reply:because scanf() extracts the first character from the input the first time, but leaves the end of line char there. The second time around the eol gets extracted from the input without any delay.


Use gets() or (better) fgets() instead - just read the whole line into the buffer, and then look at the first character.
Reply:Start your program with flushall() or flush(stdout)/ flush(stdin) ..It will clear the buffer that is occupied by scanf function..


No comments:

Post a Comment