C + + cin input stream verbose usage

Source: Internet
Author: User

Let's look at the following code:

#include <iostream>#include <vector>#include <cstdlib>intMain () {intnum =0;STD:: vector<int>Ivec Do{STD::cout<<"Please input some numbers:"<<STD:: Endl; while(STD::Cin>> num)//always detects input stream status know how to encounter file Terminator (Ctrl + Z) or wrong inputIvec.push_back (num);if(ivec.size () = =0)STD::cout<<"error!"<<STD:: Endl; } while(ivec.size () = =0); System"Pause");return 0;}

Now we have some discussion based on this piece of code:

Run discovery, when the first input is correct, it runs correctly, and if you first enter an error (for example, CTRL + Z and press ENTER), the program goes into a dead loop:

Analyze the following reasons:
First you need to understand the use of CIN. The C + + input buffering mechanism specifies that when the user presses ENTER after typing the input, all the one-time input from the user is sent to the buffer at once, and Cin reads the data from the input buffer. The carriage return flag completes the input once, and if the data is insufficient, it waits for the user to continue typing, and if the data is redundant, the excess data is stored in the input stream buffer for the next use.
As an example:

while(std::cin >> num)//一直检测输入流状态知道遇到文件结束符(ctrl+z)或错误输入  std::coutstd::endl;

This statement, if entered 1 2 3 at a time, the result of the execution is:

1

2

3

The execution process is as follows:

The first run std::cin >> num time, the input buffer is empty when the user enters 1 2 3 Ctrl + Z and then enter, when CIN reads the first integer 1, then outputs 1 and line breaks, the next time the std::cin >> num buffer is not empty, the user is no longer required to input, directly read the second integer 2, Then output 2 and line break. And so on, output 3, 4, in turn.

Then CIN checks to the end of the file flag Ctrl+z,cin>>num returns false and loops out.

It is important to note that when there is residual data in the buffer, CIN reads the buffer data directly and does not request keyboard input. It is important that the carriage return will also be present in the input buffer.

With this knowledge, you can explain the phenomenon in the previous code. If you do not enter a valid character for the first time, with CTRL + Z plus the ENTER key, the carriage return is stored as a character in the input buffer. When the loop is reached, while(std::cin >> num) Cin reads the file terminator (Ctrl + Z), the status of CIN is set 0, no longer receives input, so ivec.size() equals 0, the program enters the next loop again, because CIN no longer accepts input, ' so the program goes into a dead loop. (The reason that someone said "enter" before, but in fact not, before the second read of CIN, CIN no longer accepts input)

So we need to make a little bit of the code change:

intMain () {intnum =0;STD:: vector<int>Ivec Do{STD::cout<<"Please input some numbers:"<<STD:: Endl; while(STD::Cin>> num)//always detects input stream status know how to encounter file Terminator (Ctrl + Z) or wrong inputIvec.push_back (num);STD::Cin. Clear ();//Add this line.       if(ivec.size () = =0)STD::cout<<"error!"<<STD:: Endl; } while(ivec.size () = =0); System"Pause");return 0;}

The modified code works fine

Added in the code std::cin.clear(); , this function has two functions:
I, used to change the status identifier of CIN, CIN sets the status bit good when it receives the wrong input. If the good bit is not 1, CIN does not accept the input. If the status bit does not change the next time the input is entered, it cannot be entered even if the buffer stream is cleared. So when the input stream has an error, you must add std::cin.clear () If you want to enter it again.
II, with the role of clear buffer.

Std::cin.ignore () This function does not have the ability to change the CIN status identifier, if the Std::cin.clear () function in the above code is replaced with Std::cin.ignore, the program will still enter the dead loop if the first input is incorrect:

Ii
Then we discuss the second question and modify the following code:

intMain () {intnum =0, Val1 =0;STD:: vector<int>Ivec Do{STD::cout<<"Please input some numbers:"<<STD:: Endl; while(STD::Cin>> num)//always detects input stream status know how to encounter file Terminator (Ctrl + Z) or wrong inputIvec.push_back (num);STD::Cin. Clear ();if(ivec.size () = =0)STD::cout<<"error!"<<STD:: Endl; } while(ivec.size () = =0);STD::Cin>> Val1;STD::cout<< Val1; System"Pause");return 0;}

After running input 1 2 3 Ctrl + Z and then enter, that's all right:

The program will not wait for you to input, directly output the initial value of Val1 0, which is why?
Previously said: When there is residual data in the buffer, CIN reads the buffer data directly and does not request keyboard input. And importantly, the carriage return will also be present in the input buffer.
After the program has been run input 1 2 3 Ctrl + Z then enter,while (std::cin >> num) always detects the input stream until CIN reads to the file terminator (Ctrl + Z), the loop ends, 1, 2, and 3 are read sequentially and removed from the buffer. Leaving a enter also waits for the input stream in the buffer, so when executing std::cin >> val1 This statement, CIN will go to the buffer to read the data, read to enter after entering the end, so cout direct output Val1 initial value 0.

So we need to make the following modifications to the code:

intMain () {intnum =0, Val1 =0;STD:: vector<int>Ivec Do{STD::cout<<"Please input some numbers:"<<STD:: Endl; while(STD::Cin>> num)//always detects input stream status know how to encounter file Terminator (Ctrl + Z) or wrong inputIvec.push_back (num);STD::Cin. Clear ();if(ivec.size () = =0)STD::cout<<"error!"<<STD:: Endl; } while(ivec.size () = =0);STD::Cin. Ignore ();//Add this sentence    STD::Cin>> Val1;STD::cout<< Val1; System"Pause");return 0;}

Add Std::cin.ignore () after the while loop to clear the contents of the buffer before executing std::cin >> val1, and the program will run normally.

But here there is a problem, in the user input multiple times enter Enter, the program does not appear input error, waiting for the user input, until there is normal data input:

It is worth saying that when the CIN statement is executed, enter may be treated as a continuous space character, or it may be treated as a terminator, which is determined by the definition of CIN, and is ignored as contiguous spaces.

We can come to the top of the test, which causes the program to enter the dead loop,
Add a second while (Std::cin >> num) in the code above Std::cin.ignore.

, while (std::cin >> num) no longer accepts input after it receives a file terminator, it outputs the initial value of Val1, Val2, 0. If there is a reason for leaving a enter inside, then it is possible to val1 the end of the input, but both end the input at the same time.
The same is true of four:

Add Std::cin.ignore () to remove the remaining in the buffer of enter also not:

So the beginning of the program into the dead Loop reason, is CIN read to the file Terminator (Ctrl + Z), CIN status is set 0, no longer receive input, so ivec.size() has been equal to 0, into the dead loop, that is.

The above can actually be summed up into three points:
1, when Cin received the wrong input, its status will be changed, no longer receive input, only with cin.clear () The good status of Cin back to 1, in order to receive input normally.
2. Enter the type entered will also be stored in the buffer.
3. Enter is sometimes read as a continuous space, and sometimes it is read as a terminator, which is determined by Cin's own judgment.

C + + cin input stream verbose usage

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.