C ++ Input

Source: Internet
Author: User

Vector <int> iv1, iv2;
Cout <"Please fill in an integer element for the first vector container, ending with s:" <endl;
Int num = 0;
While (cin> num)
{
Iv1.push _ back (num );
}
Print (iv1.begin (), iv1.end (); // print the container Function

// Cin. clear ();
// Cin. sync ();

Cout <"Please fill in an integer element for the second vector container, ending with s:" <endl;
While (cin> num)
{
Iv2.push _ back (num );
}
Cout <"iv2:" <endl;
Print (iv2.begin (), iv2.end ());

The code above skips the loop directly when entering data for the first container and then the second container.

The following is an example of my debugging process:

1. Add cin. clear () for debugging, which is invalid. // The clear function is used to correct the error state. Because the first cycle contains cin> num, the type corresponding to input s is incorrect, so there will be an error state.

2. added cin. get () or invalid. My idea is whether the character "s" I entered is still in the buffer zone, using cin. get (), still failed to eat...

3. You can use the c language to clear the buffer: scanf ("% * [^ \ n]"); scanf ("% * c"); useless...

4. Baidu searched and found a function cin. sync (). accurately speaking, it is the sync () function, which perfectly solves the problem. This is the buffer clearing function of the input stream.

5. When I completed the backup function this morning, I thought about it carefully. Did I actually clear the character s when I used cin. get () yesterday? No !!! Because I have a enter key after hitting s, it takes two cin. get () characters to eat s.

In short, cin. clear () indicates the clearing error state. cin and sync () indicate the clearing buffer.

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.