How to Take Multiple Line String Input in C++?
Last Updated :
01 Feb, 2024
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++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str;
vector<string> s;
cout << "Enter multiple lines of text: " << endl;
while (getline(cin, str)) {
if (str.empty()) {
break ;
}
s.push_back(str);
}
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
Share your thoughts in the comments
Please Login to comment...