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.