Open In App

How to Take Multiple Line String Input in C++?

In C++, taking string input is a common practice but the cin is only able to read the input text till whitespace. In this article, we will discuss how to read the multiple line of text input in C++.

For Example,



Input:
Enter Your Text: This is a
multiline text.
Output:
You Have Entered:
This is a
multiline text.

Reading Multiple Line String Input in C++

To read multiple lines of text input in C++, we can use the getline() function with a loop and a condition that states when you want to stop taking the input. While looping keep storing each line in a vector of string that can be used for processing later on.

C++ Program to Read Multiple Lines of Input

The below example shows how to read muti-line string input in C++.






// C++ Program to Read Multiple Lines of Input
  
#include <iostream>
#include <string>
#include <vector>
using namespace std;
  
int main()
{
    // Declare variables
    string str;
    vector<string> s;
  
    // Prompt user to enter multiple lines of text
    cout << "Enter multiple lines of text: " << endl;
  
    // Read input lines until an empty line is encountered
    while (getline(cin, str)) {
        if (str.empty()) {
            break;
        }
        s.push_back(str);
    }
  
    // Display the entered lines
    cout << "You entered the following lines: " << endl;
    for (string& it : s) {
        cout << it << endl;
    }
  
    return 0;
}

Output

Enter multiple lines of text: 
Hello! Geek
Welcome to GeeksforGeeks
Learn to code
You entered the following lines:
Hello! Geek
Welcome to GeeksforGeeks
Learn to code
Article Tags :