Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multiple lines from keyboard as input

Tags:

c++

For my code, i had to read multiple lines from keyboard. The code i have here does the job. here is the code:

#include <iostream>

using namespace std;

int main()
{

string input;
string line;

cout<< "Enter the input line" << endl;

while (getline(cin, line))
{
    if (line == "^D")
        break;

    input += line;
}

 cout<< "The input entered was: "<<endl;
 cout<< input<< endl;

}

The output i get after running this.

Enter the input line
Hello
World !
The input entered was: 
HelloWorld !

The problem: As you see, the getline does give a white space when printing Hello World. How to make sure it gets printed as "Hello World !" rather than "HelloWorld !" This happens when there is n newline. It is concatenated with the previous line string and printed.

like image 678
Tuffy Avatar asked Feb 17 '23 13:02

Tuffy


1 Answers

Try this,

while (getline(cin, line)) {
    if (line == "^D")
        break;

    input += " " + line;
}
like image 95
Arun Avatar answered Feb 24 '23 13:02

Arun