【问题标题】:Reading piped input with C++使用 C++ 读取管道输入
【发布时间】:2011-07-23 16:50:29
【问题描述】:

我正在使用以下代码:

#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;
      }
      

      【讨论】:

      • 这不允许您在之后进行用户输入。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-13
      • 2013-11-04
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多