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.
Try this,
while (getline(cin, line)) {
if (line == "^D")
break;
input += " " + line;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With