How do I empty the input buffer using the C language? Here are a number of ways to learn

Source: Internet
Author: User
Tags stdin
There are several basic input functions in the C language:



// Get character series
int fgetc (FILE * stream);
int getc (FILE * stream);
int getchar (void);
// Get the row series
char * fgets (char * restrict s, int n, FILE * restrict stream);
char * gets (char * s); // May cause overflow, use fgets instead.
// format input series
int fscanf (FILE * restrict stream, const char * restrict format,…);
int scanf (const char * restrict format,…);
int sscanf (const char * restrict str, const char * restrict format,…);



This only discusses the use of input functions in the case of standard input (stdin). Throughout the above input functions,


    • Gets the first three functions of the character series fgetc, Getc, GetChar. In GetChar, for example, when the stdin buffer is empty, wait for input until the return-to-line function returns. If the stdin buffer is not empty, GetChar returns directly. GetChar returns a character from the buffer and converts it to an int, returning this int value.


MINGW 4.4.3 File Structure source code :

 _iobuf

{

char*_ptr;//point to current buffer read location

int_cnt;//remaining data length in buffer

Char*_base;

Int_flag;

Int_file;

Int_charbuf;

Int_bufsiz;

Char*_tmpfname;

} FILE;


Each compiler implementation may be different, and getting the character series functions here only uses _ptr and _cnt.



MINGW 4.4.3 in GetChar () implementation :


__crt_inline int __cdecl __mingw_nothrow getchar (void)

{

  Return (--stdin->_cnt >= 0)

    ?  (int) (unsigned char) *stdin->_ptr++

    : _filbuf (stdin);

}


Where stdin is the file pointer type, in MinGW 4.4.3, getc () and GetChar () are implemented as inline functions, and fgetc () is implemented as functions. By the way, the C99 standard has been added to the support of the inline function.


    • Gets the fgets and gets of the row series , where the Get function is not recommended or discussed, because gets cannot determine the buffer size and often results in overflow conditions. For the fgets function, Fgets returns each time you enter a carriage return. When Fgets returns successfully, the data in the input buffer is copied into the space pointed to by the first argument, with the line feed character ' \ n '. If the input data exceeds the buffer length, fgets intercepts the data to the first n-1 (n is the second parameter of Fgets, points to the length of the space for the first argument), and then adds ' \ n ' at the end. So the fgets is safe. Usually with fgets (buf, Buf_len, stdin), instead of gets (BUF);.

    • Formatting input from a file stream in a formatted input series is not fscanf. Commonly used or scanf, formatted input series function to enter data (depending on the function may be the standard input may also be a string input, such as: sscanf) before the white space characters (spaces, tabs, line breaks) until the non-whitespace characters are encountered, It then attempts to parse non-whitespace characters and subsequent characters according to the format parameters. The series function returns the number of variables that successfully resolved the assignment, and returns EOF if a file tail or error is encountered.


================= Split Line =================



Referring to buffers, you have to mention setbuf and setvbuf two buffer set functions, which are declared as follows:


SETBUF (FILE * Restrict Stream,  * restrict buf);

int setvbuf (FILE * Restrict Stream, char * restrict buf, int mode, size_t size);




The mode parameters of the setvbuf are:


    • _IOFBF (full buffering): Buffers are read into data when empty, and data is written to the stream when the buffer is full.

    • _IOLBF (Row buffer): reads a row of data from the stream or writes data to the stream each time. such as:stdio,stdout

    • _IONBF (unbuffered): reads data directly from the stream, or writes data directly to the stream without a buffer. such as:stderr


setbuf (Stream, buf); in:


    • BUF = = NULL: equivalent to (void) setvbuf (stream, NULL, _IONBF, 0);

    • BUF points to a buffer of length bufsiz : equivalent to (void) setvbuf (stream, buf, _IOFBF, Bufsiz);


Note:bufsiz macros are defined in stdio.h.



Here also to mention the legendary setbuf of the Classic error , in the "C Traps and defects" mentioned:


Main ()

{

    int C;

    Char Buf[bufsiz];


    Setbuf (STDOUT,BUF);

    while ((c = GetChar ())! = EOF)

        Putchar (c);

    

    return 0;

}



The problem is this: the C run-time library must clean up before the program returns control to the operating system, partly by refreshing the output buffer, but at this point the main function is finished, and the BUF buffer scope is in the main function, when the BUF character array is released. Causes the output to be garbled.



Solution: You can set buf to static, or global variables, or call malloc to dynamically request memory.



================= Split Line =================



Here's a look at several popular buffer emptying methods:


    • Fflush (stdin);


By the C99 standard document:


If stream points to an output stream or a update stream in which the most recent

Operation is not input, the Fflush function causes any unwritten data for that stream

To being delivered to the host environment to being written to Thefile; Otherwise, the behavior is

undefined.



It can be seen that the behavior of the input stream as a parameter is not defined by Fflush . However, it is defined by Fflush on MSDN:

If the file associated with stream are open for output, Fflush writes to that file the

Contents of the buffer associated with the stream. If the stream is open for input,

Fflush clears the contents of the buffer.



Can see Fflush (stdin) on the VC or effective! Fflush (stdin) is not recommended to flush the input buffers, since each compiler does not implement the undefined behavior of fflush.



Setbuf (stdin, NULL);



By the introduction of the front facing setbuf function, it can be learned that setbuf (stdin, NULL), is to make the stdin input stream from the default buffer to no buffer . There is no buffer, of course, the buffer data residue problem will be resolved. But that's not what we want.



scanf ("%*[^\n]"); formula (referred to in the second edition of the Modern method of C language programming)



This uses the "*" in the scanf formatter, which is the assignment mask; "%[^ collection", which matches any sequence of characters that are not in the collection. This also brings up a problem where the newline character ' \ n ' in the buffer will stay, requiring additional action to discard the newline character separately.



Classic style

C

while ((c = GetChar ())! = ' \ n ' && c! = EOF);




Known by the code, keep using GetChar () to get the characters in the buffer until the character C is the line break ' \ n ' or the end of file is EOF. This method can perfectly erase the input buffer and is portable.



Related articles:



Disable page Caching methods disable page caching in multiple languages



How to bulk clean up the system temp files (language: C #, C + +, PHP, Python, Java)



Related videos:



C Language Tutorials


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.