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!
You can also choose between isblank() which recognizes blanks and tabs, and isspace() which recognizes blanks, tabs, newlines, formfeeds, carriage returns and vertical tabs ( " \t\n\f\r\v" ).
Simple. Use fgets. Check the buffer to see if it contains only a newline (or alternately, only whitespace and a newline). Or fgets + sscanf, and see if sscanf returns what you expect.
fgets returns at most nchar characters of the next line. If the number of characters specified by nchar includes characters beyond the newline character or the end-of-file marker, then fgets does not return any characters beyond the new line character or the end-of-file marker.
fgets() function in CThe function reads a text line or a string from the specified file or console. And then stores it to the respective string variable. Similar to the gets() function, fgets also terminates reading whenever it encounters a newline character.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With