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.
问题:如你所见,getline确实在打印Hello World时给出了空格。如何确保它被打印为“Hello World!”而不是“HelloWorld!”当有新换行符时会发生这种情况。它与前一行字符串连接并打印。
1 个解决方案
#1
4
Try this,
while (getline(cin, line)) {
if (line == "^D")
break;
input += " " + line;
}
#1
4
Try this,
while (getline(cin, line)) {
if (line == "^D")
break;
input += " " + line;
}