[C Language] clears the cache.

Source: Internet
Author: User

Clear the cache in stdin

Int C;

While (C = getchar ())! = EOF & C! = '\ N ');

The cache is cleared, but '\ n' (10) is left behind)

When reading, you can use scanf ("% [^ \ n]", c); To empty \ n.

Or scanf ("\ n % d", C );

 

 

Failed solution:

1,

While (! Feof (stdin )){

Getchar ();

}

Result:ProgramIt will be stuck in this section and will never generate a while loop.

Because the feof (File * file) function must wait until the data cannot be read for the next time, non-0 is returned. For example, when reading an empty file, the returned value of feof (File) is 0, use

After the fread () function, although nothing is read, feof (File) returns non-0;

Therefore, although the end is reached, the returned value of feof (stdin) is still 0, and the program will be stuck in getchar (), waiting for input.

 

2,

Fflush (stdin );

Invalid after use. Check that this function is not a standard function and can be used by VC compiler, but other compilers such as GCC do not support it (Note: fflush (stdout) is a standard function)

 

3,

While (C = getchar ())! = EOF & C! = '\ N'); the first character in the buffer zone is' \ n '.

Scanf ("% * [\ n] % d", c); at this time, c reads \ n, but does not read the following input, resulting in a program error.

 

I don't want to understand why, % [\ n] is not stopped when I read the first non \ n. I can ignore this with an asterisk, and then % d can read the input. The result is incorrect. Thank you!

 

4,

Use setbuf (stdin, null); clear Cache

The function prototype of setbuf is

Void Setbuf ( File * Stream , Char * Buf ) ;

 

 

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.