简体   繁体   中英

How to take multiple line string input in C++?

I am learning C++. I want to take multiple line string as input but I can't. I am using getline() for it but it is taking only one line input. When I press enter for writing next line it stoped taking input and print the first line.

I want to give input like the example below

Hello, I am Satyajit Roy.
I want to make a program.
I love to travel.

But it takes only the first line input.

My code:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s;
    getline(cin, s);
    cout << s << endl;

    return 0;
}

Please help me to know how can I do that. Thank you.

Either you write a loop to read individual lines and concatenate them to a single string, thats what this answer suggests. If you are fine with designating a specific character to signal the end of the input, you can use the getline overload that takes a delimiter as parameter:

#include <iostream>
#include <string>


int main() {
    std::string s;
    std::getline(std::cin,s,'x');
    std::cout << s;
}

The user would have to type an x to end input, so this input

Hello, I am Satyajit Roy.
I want to make a program.
I love to travel.
x

would result in this output:

Hello, I am Satyajit Roy.
I want to make a program.
I love to travel.

Of course this won't work when the string to be entered contains x , which renders the approach rather useless.

However, instead of using a "real" character as delimiter you can use the EOF character (EOF = end of file) like this:

 std::getline(std::cin, s, static_cast<char>(EOF));

Then input is terminated by whatever your terminal interprets as EOF , eg Ctrl-d in linux.

Thanks to @darcamo for enlightening me on the EOF part.

You can only read one line at a time with std::getline if you don't provide your own delimiter. If you want to accumulate multiple lines, one at a time, you need a place to put the result. Define a second string. Read a line at a time into s with std::getline , and then append s to the result string. Like this:

std::string result;
std::string s;
while (std::getline(std::cin, s))
    result += s;

You can take several lines using the code below if you know how many lines you will input.

int line=3, t;
string s, bigString;

for(int i=0 ; i<line ; i++)
{
    getline(cin,s); // This is to input the sentence
    bigString += s + "\n";
}

cout << bigString;

If you don't know how many lines you will input (Input from file until end of file) then you can check this.

string s;
vector<string> all;

while(getline(cin,s))
{
     all.push_back(s);// This is to input the sentence

}

for(auto i:all)
{
    cout << i << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM