C language: C language used to clear the input buffer in the case of standard input (stdin)

Source: Internet
Author: User

C language: C language used to clear the input buffer in the case of standard input (stdin)
C language clearing input buffer in the standard input (stdin) case of use 1:

// Function: enter a number, a character, and output hello bit # include <stdio. h> int main () {int num = 0; char ch = ''; scanf (" % d ", & num); scanf (" % c ", & ch ); printf ("hello bit \ n"); system ("pause"); return 0 ;}

 

Result: 7 hello bit. Press any key to continue... analysis: If no character is entered, the "hello bit" is output directly, because when you press enter ('\ n'), it is equivalent to inputting a character, then we need to clear the buffer handler 2:
# Include <stdio. h> int main () {int num = 0; char ch = ''; scanf (" % d ", & num);/* fflush (stdin ); * /// errors are prone to errors when clearing the buffer. It is not recommended to use/* scanf ("% * [^ \ n]"); * // It is not easy to use, easy to invalidate setbuf (stdin, NULL); // converts the stdin input stream from the default buffer to a buffer-free zone. scanf ("% c", & ch) can be used ); printf ("hello bit \ n"); system ("pause"); return 0 ;}

 

Result: 5. Press any key to continue jhello bit... program 3:
// Function: enter a number, a character, and output hello bit # include <stdio. h> # define CLEAR_BUF () \ int c = 0; \ while (c = getchar ())! = EOF & c! = '\ N') \{\;\} int main () {int num = 0; char ch = ''; scanf (" % d ", & num ); CLEAR_BUF (); scanf ("% c", & ch); printf ("hello bit \ n"); system ("pause"); return 0 ;}

 

Result: 8. Press any key to continue shello bit... analysis: It is recommended that program 3 Use getchar () to obtain the buffer characters until the obtained C is "\ n" or the file Terminator EOF, this method perfectly clears the input buffer and is portable.

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.