【问题标题】:Reading piped input with C++使用 C++ 读取管道输入
【发布时间】:2023-09-20 10:20:01
【问题描述】:

我正在使用以下代码:

#include <iostream>
using namespace std;

int main(int argc, char **argv) {
    string lineInput = " ";
    while(lineInput.length()>0) {
        cin >> lineInput;
        cout << lineInput;
    }
    return 0;
}

使用以下命令: echo "Hello" | test.exe

结果是一个打印“Hello”的无限循环。如何让它读取并打印一个“Hello”?

【问题讨论】:

    标签: c++ pipe stdin cin


    【解决方案1】:

    cin 提取失败时,它不会更改目标变量。因此,您的程序最后一次成功读取的字符串都会卡在lineInput

    您需要检查cin.fail()Erik has shown the preferred way to do that

    【讨论】:

      【解决方案2】:
      string lineInput;
      while (cin >> lineInput) {
        cout << lineInput;
      }
      

      如果您真的想要完整的行,请使用:

      string lineInput;
      while (getline(cin,lineInput)) {
        cout << lineInput;
      }
      

      【讨论】:

      • 这不允许您在之后进行用户输入。