Reading C ++ empty lines

I'm having trouble reading and differentiating blank lines from input.

Here is the sample input:

number string string string ... number string string ... 

Each number represents the beginning of the input and an empty line after the sequence of lines represents the end of the input. A string can be a phrase, not just 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 tried directly cin -> blank, but that didn't work.

Can someone help me solve this problem?

Thanks!

+5
source share
1 answer

After you read the number with this line:

 while(cin >> n) { //number 

cin does not read anything after the last digit. This means that the cin input buffer still contains the rest of the line in which the number was included. So you need to skip this line and the next empty line. You can do this simply by 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 } } 
+5
source

Source: https://habr.com/ru/post/1201524/


All Articles