简体   繁体   中英

why doesn't the getline() terminate when I input a newline?

I have this code:

string sentence2;
while(getline(cin, sentence2)){
    // while there are lines coming in
    cout << sentence2 << endl;
}

on VSCode, I put my final input as an empty line by pressing "Enter" key. The code returned an empty line. Why doesn't the loop terminate instead?

You can add a condition to check that the line is not empty:

string sentence2;
while(getline(cin, sentence2) && not sentence2.empty()){
    // while there are lines coming in
    cout << sentence2 << endl;
}

std::getline returns a reference to cin and cin will be in a failed state if it wasn't able to read anything - but even an empty line requires a successful read (of \n ) so that won't set it in a failed state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM