2013-05-13 57 views
2

对于我的代码,我不得不从键盘读取多行。我在这里的代码完成了这项工作。这里是代码:从键盘读取多行作为输入

#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!” 发生n换行时会发生这种情况。它与前一行字符串连接并打印。

+1

你意识到,以字符串' “^ d” 比较'不会CTRL-d比较,对不对? CTRL-D(在Linux/Unix类型的操作系统中)将以文件末尾结束输入,所以你不能(通常)看到它。即使如此,比较应该是针对值4的一个字符。 – 2013-05-13 07:08:30

回答

4

试试这个,

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

    input += " " + line; 
}