【问题标题】:C++: Read from stdin as data is written into pipeC ++:在将数据写入管道时从标准输入读取
【发布时间】:2015-04-17 01:36:23
【问题描述】:

我有两个 C++ 程序:一个将消息打印到 stdout,另一个侦听 stdin 并打印流中的所有内容。它们分别被命名为outin

out.cpp:

#include <iostream>

using namespace std;

int main() {
        cout<<"HELLO";
        usleep(1000000);
        cout<<"HELLO";
}

in.cpp:

#include <iostream>

using namespace std;

int main() {
        string input;
        while(cin>>input) {
                cout<<input;
        }
}

就目前而言,将数据从out 传送到in 等待两秒钟,然后打印HELLOHELLO

~$ ./out | ./in

#...two seconds later:
~$ ./out | ./in
HELLOHELLO~$

我确定这是一个简单的问题,但 in 是否可以像 out 一样打印每个 HELLO?我读过piped commands run concurrently,但对于这种特殊情况,我一定是误解了这个概念。期望的性能是:

~$ ./out | ./in

#...one second later:
~$ ./out | ./in
HELLO

#...one second after that:
~$ ./out | ./in
HELLOHELLO~$

【问题讨论】:

    标签: c++ bash piping


    【解决方案1】:

    这里有两个问题。

    首先是输出缓冲。你需要flush the output stream。 可能最简单的方法是cout.flush()

    第二个是字符串读取读取整个单词,你只输出一个,中间有停顿。

    您要么需要切换到基于字符的输入,要么在单词之间放置一个分隔符。

    基于字符的输入如下所示

    int main() {
            char input;
            while(cin>>input) {
                    cout<<input;
            }
    }
    

    添加分隔符如下所示:

    int main() {
            cout<<"HELLO";
            cout<<" ";
            usleep(1000000);
            cout<<"HELLO";
    }
    

    注意额外的空间。

    【讨论】: