How to clear scanf () cache in C Language

Source: Internet
Author: User

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!


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.