C ++:将数据写入管道时从stdin读取 [英] C++: Read from stdin as data is written into pipe

查看:90
本文介绍了C ++:将数据写入管道时从stdin读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two C++ programs: one that prints a message to stdout, and the other that listens to stdin and prints all content from the stream. They are named out and in respectively.

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 :

As it currently stands, piping the data from out to in waits for two seconds, then prints HELLOHELLO:

~$ ./out | ./in

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

我确定这是一个简单的问题,但是在 out 打印时, in 是否可以打印每个 HELLO ?我读过 piped命令同时运行,但是我必须针对这种特殊情况误解此概念.所需的性能是:

I'm sure this is a simple question, but is it possible for in to print each HELLO as out prints it? I've read that piped commands run concurrently, but I must be misunderstanding this concept for this particular situation. The desired performance is:

~$ ./out | ./in

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

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

推荐答案

这里有两个问题.

第一个是输出缓冲.您需要刷新输出流.可能最简单的方法是 cout.flush().

The first is output buffering. You need to flush the output stream. Probably easiest way is cout.flush().

第二个是字符串读取,它读取整个单词,而您只输出一个,中间有一个停顿.

The second is string reading reads whole words, and you're only outputting one, with a pause between.

您要么需要切换到基于字符的输入,要么在单词之间使用分隔符.

You either need to switch to character based input, or put a separator between the words.

基于字符的输入如下所示

Character based input would look like this

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

添加分隔符如下所示:

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

请注意额外的空格.

这篇关于C ++:将数据写入管道时从stdin读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆