C++:在数据写入管道时从标准输入读取

标签 c++ bash piping

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

输出.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~$

最佳答案

这里有两个问题。

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

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

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

基于字符的输入看起来像这样

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

添加分隔符如下所示:

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

注意额外的空间。

关于C++:在数据写入管道时从标准输入读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29688737/

相关文章:

c++ - 在 VC 2015 上使用带有字符串的宏失败

linux - 如何在 bash 的每个子目录中创建相同的目录?

linux - 将数值结果从单个文本文件分离到 linux 中的多个文件

audio - 使用 sox splice 对一组音频文件进行淡入淡出

c++ - 一个可执行文件的“连续”C++ 输出作为另一个程序的输入

c++ - g++错误,无法识别的选项,--subsystem console“在ubuntu的eclipse中

c++ - 需要帮助编码霍夫曼树

c++ - 写入 const API 函数中的成员变量 (C++)

linux - Bash脚本SSH命令变量插值

bash - 捕获 getopt 无效选项