C: C language emptying input buffers for use in standard input (stdin) cases

Source: Internet
Author: User
Tags stdin

the C language empties the input buffer use in standard input (stdin) Cases

Program 1:

Function: First enter a number, then enter a character, 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;

}

Results:

7

Hello bit

Please press any key to continue ...

Analysis: There is no input character, the output is directly " Hello bit "Because when you click Enter ('\ n'), it is equivalent to entering a character, then we need to clear the buffer processing

Program 2:

#include <stdio.h>

int Main ()

{

int num = 0;

Char ch = "' ;

scanf ("%d", &num);

/*fflush (stdin); * * //Empty buffer error prone, not recommended

/*SCANF ("%*[^\n]"); *///is not good, easy to fail

setbuf (stdin, NULL); //enable the stdin input stream to be converted from the default buffer to no buffer

scanf ("%c", &ch);

printf ("Hello bit\n");

System ("pause");

return 0;

}

Results:

5

J

Hello bit

Please press any key to continue ...

Program 3:

Function: First enter a number, then enter a character, 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;

}

Results:

8

S

Hello bit

Please press any key to continue ...

Analysis: Program 3 recommended to use, keep using GetChar () gets the characters in the buffer until the obtained C is "\ n" or the end of file is EOF, this method perfectly clears the input buffer and is portable


This article is from the "Rock Owl" blog, please be sure to keep this source http://10742111.blog.51cto.com/10732111/1720583

C: C language emptying input buffers for use in standard input (stdin) cases

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.