我有两个 C++ 程序:一个将消息打印到标准输出,另一个监听标准输入并打印流中的所有内容。它们分别被命名为out
和in
。
输出.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/