Sam Sam -4 years ago 54
C++ Question

C++ getline(cin, buffer) doesn't stop when I press CTRL+Z

I assume the end of input is when user presses Ctrl+Z (that imitates

EOF
).

When I enter "qwe" and press Ctrl+Z the
getline
instead of just assigning the "qwe" to
tmp
asks me to input one more line for some reason. However, the resulting value in
tmp
is still "qwe" ignoring the extra line. The code I use is the following:

string tmp;
getline(cin, tmp);


UPD (8 months later):

I apologize for the badly explained question in the past. The solution, as it was said in C++ Issue with cin and CTRL + Z, is it's just the usual Windows behavior, where the Ctrl+Z symbol
must
be at the beginning of the line or it will not work.

If you type "qweCtrl+Z", the program will ask you for the extra line to input. And you input "erty" the
tmp
will still have only the "qwe".

If you type "qweEnterCtrl+Z", the program will assign "qwe" to
tmp
and stop.

To get multiline input you should use cycle and search for
'\n' || EOF
.

Answer Source

As explained by OP: This is typical Windows behavior, where the Ctrl+Z symbol must be at the beginning of the line or it will not work as expected.

So if you input "foo", then send the EOF signal by pressing Ctrl+Z and then input "bar", "foo" will be read as expected and then EOF will wait in the input buffer until "bar" is typed too. The program, as is, will stop at EOF and "bar" will be ignored, even though the user typed it.

Read more in C++ Issue with cin and CTRL + Z.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download