c++ - 从键盘读取多行作为输入

标签 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 !

问题:如您所见,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/

相关文章:

c++ - 'this'指针如何用作成员函数的参数

c++ - 大型 C++ 项目的文件/文件夹布局的最佳实践是什么

c++ - 多线程 std::shared_ptr 读/写

c++ - (class) 没有命名类型

c++ - Type cv::StereoBM 必须实现继承的纯虚方法

c++ - 我应该如何遍历 C++ 中的二进制文件?

c++ - 如何从 vector 初始化数组? (如何将指针转换为数组?)

c++ - 需要计算特定单词的实例数

c++ - 为什么我不能推断出这个函数的模板参数?

c++ - 结构指针函数指向其他结构的其他函数