Read empty lines C++
17,338
After you read the number with this line:
while(cin >> n) { //number
cin
doesn't read anything after the last digit. That means cin's input buffer still contains the rest of the line that the number was on. So, you need to skip that line, and the next blank line. You could do that by just using getline twice. i.e.
while(cin >> n) { //number
string s, blank;
getline(cin, blank); // reads the rest of the line that the number was on
getline(cin, blank); // reads the blank line
while (getline(cin, s) && !s.empty()) {
//do stuff
}
}
Author by
Larissa Leite
Updated on August 17, 2022Comments
-
Larissa Leite over 1 year
I am having trouble reading and differentiating empty lines from an input.
Here's the sample input:
number string string string ... number string string ...
Each number represents the start of an input and the blank line after the sequence of strings represents the end of an input. The string can be a phrase, not only one word.
My code does the following:
int n; while(cin >> n) { //number string s, blank; getline(cin, blank); //reads the blank line while (getline(cin, s) && s.length() > 0) { //I've tried !s.empty() //do stuff } }
I've tried directly cin >> blank, but it didn't work.
Can someone help me solve this issue?
Thanks!
-
Diffy over 8 yearsIsnt it because getLine() stops at seeing a whitespace character. So 1st getLine() will consume the whitespace character and the 2nd getLine() will consume the blank line. The solution given is anyways correct.
-
Mampac over 2 yearswhy then continuous prompting for a number doesn't result in a
cin
error; only after the last one, an empty string passed to the nextcin
? for example, if icin >> n
three times in a row, thencin >> string
, the string will be empty, but the previouscin
s didn't trigger a failure