C + + Clears the input buffer sync () vs ignore ()

Source: Internet
Author: User

Recently in the writing process is always not aware of the input buffer is still something, resulting in some anomalies, debugging for half a day. Since the last post, learn to note, warning!

Http://blog.chinaunix.net/uid-21254310-id-1828906.html

The sync () function and the Ignore () function are all used to clear the contents of the input buffer.

#include <unistd.h> void sync (void) clears the input buffer

#include <iostream> IStream &ignore (streamsize num=1, int delim=eof);   The characters are read until NUM characters have been read (default is 1) or until the character Delim is read (default is EOF). Its invocation form is Cin.ignore (n, terminating character)

Since the program runs without always knowing the progress of the external input, it is difficult to control whether the contents of the input buffer are cleared . Usually we might just want to discard some of the input buffers, not all of them. For example, clear the current line, or clear the end of the line break, and so on. But if the next line is already in the buffer, this part may be something we want to keep. You might consider using the Ignore function instead (because sync always gets rid of everything)

  Cin.ignore (Numeric_limits::max (), ' \ n ');//clear When moving forward

Cin.ignore (Numeric_limits::max ()); Clear all content in CIN

  Numeric_limits::max () is the maximum value used by the stream defined by the Climits header file, and you can replace it with a large enough integer.

Using ignore can obviously control the buffer more precisely than sync (). and ignore () can be used to clear a character. However, this does not use much, for clearly know to discard a character, it can be done by the program to read the operation, and then discard the read content to implement.

C + + Clears the input buffer sync () vs ignore ()

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.