使用 C++ 读取管道输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5446161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:11:07  来源:igfitidea点击:

Reading piped input with C++

c++pipestdincin

提问by Erik

I am using the following code:

我正在使用以下代码:

#include <iostream>
using namespace std;

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

With the following command: echo "Hello" | test.exe

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

Thes result is an infinate loop printing "Hello". How can I make it read and print a single "Hello"?

结果是无限循环打印“你好”。我怎样才能让它读取和打印一个“你好”?

回答by Erik

string lineInput;
while (cin >> lineInput) {
  cout << lineInput;
}

If you really want full lines, use:

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

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

回答by Ben Voigt

When cinfails to extract, it doesn't change the target variable. So whatever string your program last read successfully is stuck in lineInput.

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

You need to check cin.fail(), and Erik has shown the preferred way to do that.

您需要检查cin.fail()Erik 已经展示了执行此操作的首选方法