对于我的代码,我必须从键盘读取多行。我这里的代码可以完成这项工作。这是代码:
#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;
}
运行后得到的输出。
Enter the input line
Hello
World !
The input entered was:
HelloWorld !
问题:如您所见,getline 在打印 Hello World 时确实给出了一个空白。如何确保它被打印为“Hello World!”而不是“HelloWorld!” 当有 n 个换行符时会发生这种情况。它与前一行字符串连接并打印。
最佳答案
试试这个,
while (getline(cin, line)) {
if (line == "^D")
break;
input += " " + line;
}
关于c++ - 从键盘读取多行作为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16516461/