How to clear scanf () cache in C Language
(1) The cache clearing function is:
void safe_flush(FILE *fp){int ch;while( (ch = fgetc(fp)) != EOF && ch != '\n' ); }
(2) then we can directly call it when using it:
scanf("%d",&k);safe_flush(stdin);
In this way, you can clear the cache problems!
(3) Case Study
A. When we do not clear the hazards caused by scanf:
# Include
# Include
Int main () {int k; printf ("Enter your key: (integer)"); scanf ("% d", & k); char c; printf ("enter a character:"); c = getchar (); printf ("% d", k); printf ("% c", c );}
We found that when we input an integer, the program is automatically ended and the entered value is cached to the character c.
Then we clear the cache:
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHByZSBjbGFzcz0 = "brush: java;"> # include # Include // Used to clear the impact of the Enter key cache void safe_flush (FILE * fp) {int ch; while (ch = fgetc (fp ))! = EOF & ch! = '\ N');} int main () {int k; printf ("Enter your key: (integer)"); scanf ("% d ", & k); safe_flush (stdin); char c; printf ("enter a character:"); c = getchar (); printf ("% d", k ); printf ("% c", c );}
After we enter an integer, We are prompted to input characters, which obviously eliminates the cache.
OK!