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

时间:2016-06-03 01:41:37

标签: c++ command-line-interface piping

我试图将一个可执行文件生成的输出作为输入传递给另一个。我能够一次发送一行。

问题是当我尝试从Program1发送'while循环中生成的行序列'时,将被Program2读取为输入。我尝试在终端中管道可执行文件(如下所示),但它无法正常工作。

./Program1 | ./Program2  
./Program1 |xargs ./Program2  
./Program1 > ./Program2  

我想避免文件I / O.

注意: 平台: Linux

==================

以下示例的内容

Program1(写入终端)

int main(int argc, char *argv[])
{
    int i = 2200;
    while(1){    
        printf("%d \n", i);
        i++;
    }
}

Program2(从终端读取,Program1的输出)

int main(int argc, char *argv[])
    {   
        while(1){ 
        // Read 'i' values
        cout << "There are " << argc << " arguments:" << endl;
        // Loop through each argument and print its number and value
        for (int nArg=0; nArg < argc; nArg++)
        cout << nArg << " " << argv[nArg] << endl;
        }

        return 0;
    }

1 个答案:

答案 0 :(得分:5)

问题是您正在尝试阅读程序参数。但是当您从一个程序管道到下一个程序时,第一个程序的输出变为第二个程序的标准输入std::cin)。

尝试使用程序2:

#include <string>
#include <iostream>

int main()
{
    std::string line;

    while(std::getline(std::cin, line)) // read from std::cin
    {
        // show that it arrived
        std::cout << "Line Received: " << line << '\n';
    }
}
相关问题