Answer fooobar.com/questions/914489 / ... what happens. About why, we need to delve a little into philosophy.
The C ++ stream model is not considered for "human interaction": it is a general transformer of an almost infinite sequence of characters into a list of spatially separated "values" that must be converted to the provided "variables".
There is no concept of "input and output interleaving for dialogue." If you enter your input in a text file, for example myinput.txt
(invalid input)
ABC456 9 7.8 XYZ Y ABC456 5 6.7 XYZ N
and run the program from the command line, for example
myprogram < myinput.txt
your program will start ... and there is no need for a βpauseβ to see the result, since no one is sitting there to see it and answer it.
The program stops to wait for user input not because of cin >>
, but because cin
not in a failed state, and the buffer is empty, and the console is the source for resetting the buffer. This is a console that waits for "\ n" before returning, not cin.
When cin >> n
is called ...
- function
operator>>
is called, and it ... - gets the num_get face from the stream locale and calls the get function, which ...
- call the
sbumpc
stream buffer several times to get the numbers and calculate the value of the number. - If the buffer has content, it simply returns its characters one by one. When the character is no longer present (or if it is empty) ...
- The buffer requests the operating system to read from a low-level file.
- If the file is a console, the editor of the console internal line is called:
- This causes the console to linger, allowing the user to press a character and some controls (e.g. backspace, for example) until a key is pressed
- The console line editor returns the line to the operating system, which will allow the contents of the available input CON file ...
- This is read by the buffer (after transmitting the read characters to the cvt locale plot, but this is detailed information), which is filled in by itself.
- Now make yourself return the U-turn.
This whole mechanism is made by the fact that - if you enter more than required, the contents of the buffer remain available for the next calls >>
, regardless of whether it is another program or not.
It requires the correct "safe" disassembly, confirmation of input, the status of the stream to be cleaned, and the next content that must be ignored until the next '\n'
. This is usually done using
cin.clear(); cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
Thus, everything that was printed is discarded, and the next cin>>
finds the buffer without data (only '\n'
, which is truncated as the "initial space"), forcing the console to go into the queue, edit the mode again.