用C++读取管道输入

12 c++ stdin pipe cin

我使用以下代码:

#include <iostream>
using namespace std;

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

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

结果是无限循环打印"Hello".如何让它读取并打印单个"Hello"?

Eri*_*rik 25

string lineInput;
while (cin >> lineInput) {
  cout << lineInput;
}
Run Code Online (Sandbox Code Playgroud)

如果你真的想要完整的线条,请使用:

string lineInput;
while (getline(cin,lineInput)) {
  cout << lineInput;
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*igt 12

cin无法提取,它不会改变目标变量.因此,无论你的程序最后成功读取的字符串是什么lineInput.

您需要检查cin.fail(),Erik已经展示了这样做的首选方式.