Read multiline string input in C++
This post will discuss how to read multi-line string input in C++.
The std::getline function extracts characters from the input stream and stores them into a specified stream until a delimiter is encountered. The idea is to read each line at a time with std::getline and store them in a container. If no delimiter is specified, use an empty line as a delimiter character.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <vector> #include <string> int main() { std::string line; std::vector<std::string> v; while (std::getline(std::cin, line)) { if (line.empty()) { break; } v.push_back(line); } for (std::string &s: v){ std::cout << s << std::endl; } return 0; } |
The above solution repeatedly read lines with std::getline using a loop, and store each line as an element in a vector of strings. We can read the entire text in a single string by using the overload version of the std::getline function that accepts a delimiter character to signal the end of the input:
For example, the following solution reads the multiline input from the console into the string s using std::getline until the $ character is encountered, which gets interpreted as EOF.
|
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <string> int main() { std::string s; std::getline(std::cin, s, '$'); std::cout << s << std::endl; return 0; } |
We can even use the actual EOF (End-of-File) indicator as a delimiter. Now, the input is terminated when the end-of-File indicator associated with the input stream is set.
|
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <string> int main() { std::string s; std::getline(std::cin, s, static_cast<char>(EOF)); std::cout << s << std::endl; return 0; } |
That’s all about reading multi-line string input in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)