msapere
msapere

Reputation: 191

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?

Upvotes: 0

Views: 480

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117328

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.

Upvotes: 3

Related Questions