Answer https://stackoverflow.com/a/10379322/924727 expalins what happens.
About the why, we must go a bit into philosophy.
The C++ stream model is not thought for "human interaction": it is a generic converter of a virtually infinite sequence of characters into a list of space separated "values" to be converted into the supplied "variables".
There is no concept of "input and output interleaving to for a dialog".
If you write your input into a text file like myinput.txt
(unsing correct input)
ABC456 9 7.8 XYZ
Y
ABC456 5 6.7 XYZ
N
and ron your program from the command prompt like
myprogram < myinput.txt
your program will run ... and no "pause" can be required to see the output, since no-one is sitting there to see it and answer it.
The program pauses to wait user input not because of cin >>
, but because cin
is not in fail state and the buffer is empty and the source the buffer remaps is the console. It is the console that waits for '\n' before returning, not cin.
When cin >> n
is called...
- the
operator>>
function is called, and it ...
- gets the num_get facet from the stream locale and call its get function that...
- call the stream buffer
sbumpc
repeatedly to get the digits and compute the number value.
- If the buffer has content, it just return its characters one after the other. When no more character are present (or if it is empty) ...
- The buffer ask the operating system to read from the low level file.
- If the file is the console, the console internal line editor is invoked:
- This makes the console to stuck letting the user press character and some controls (like the backspace, for example) until, when Enter is pressed
- The console line editor returns the line to the operating system that will let the contents available to the input CON file ...
- That is read by the buffer (after passing the read characters to the cvt locale facet, but this is a detail) that fills up itself.
- Now do yourself the returns an unrolling.
All this mechanism makes the fact that - if you type more than required - the buffer content remains available to the next >>
calls, independently it is or not another program line.
A proper "safer" parse requires, afer an input has been read, the stream state to be cleared and the following content to be ignored up to the next '\n'
.
This is typically done with
cin.clear();
cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
So that, whatever had been typed is discarded, and the next cin>>
finds a buffer with no data (just the '\n'
, that is trimmed as "beginning space"), thus causing the console to go in line edit mode again.