Open In App
Related Articles

How to use getline() in C++ when there are blank lines in input?

Improve Article
Improve
Save Article
Save
Like Article
Like

In C++, if we need to read a few sentences from a stream, the generally preferred way is to use the getline() function as it can read string streams till it encounters a newline or sees a delimiter provided by the user. Also, it uses <string.h> header file to be fully functional.

Here is a sample program in c++ that reads four sentences and displays them with “: newline” at the end 

CPP




// A simple C++ program to show working of getline
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
    string str;
    int t = 4;
    while (t--) {
        // Read a line from standard input in str
        getline(cin, str);
        cout << str << " : newline" << endl;
    }
    return 0;
}


Sample Input :

 This
 is
 Geeks
 for

As the expected output is:

This : newline
is  : newline
Geeks : newline
for : newline

The above input and output look good, there may be problems when the input has blank lines in between. 

Sample Input :

This

is 

Geeks

for

Output:

This : newline
 : newline
is  : newline
 : newline

It doesn’t print the last 3 lines. The reason is that getline() reads till enter is encountered even if no characters are read. So even if there is nothing in the third line, getline() considers it as a single line. Further, observe the problem in the second line. The code can be modified to exclude such blank lines. Modified code: 

CPP




// A simple C++ program that uses getline to read
// input with blank lines
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
    string str;
    int t = 4;
    while (t--) {
        getline(cin, str);
 
        // Keep reading a new line while there is
        // a blank line
        while (str.length() == 0)
            getline(cin, str);
 
        cout << str << " : newline" << endl;
    }
    return 0;
}


Input:

This

is 

Geeks

for

Output:

This : newline
is  : newline
Geeks : newline
for : newline

If you like GeeksforGeeks and would like to contribute, you can also write an article on write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 03 Jun, 2022
Like Article
Save Article
Previous
Next
Similar Reads