从键盘读取多行作为输入

时间:2013-05-13 07:03:15

标签: c++

对于我的代码,我必须从键盘读取多行。我在这里的代码完成了这项工作。这是代码:

#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 !

问题:如您所见,在打印Hello World时,getline确实给出了空格。如何确保它被打印为“Hello World!”而不是“HelloWorld!” 当有新换行符时会发生这种情况。它与前一行字符串连接并打印。

2 个答案:

答案 0 :(得分:4)

试试这个,

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

    input += " " + line;
}

答案 1 :(得分:1)

只需使用cin.ignore();在输入字符串示例之前:

cin.ignore();
string s;
getline(cin,s);
相关问题