mys*_*que 5 c++ command-line-interface piping
我试图将一个可执行文件生成的输出作为输入传递给另一个可执行文件。我已经能够一次发送一行。
问题是当我尝试从Program1发送“ while循环中生成的行序列”以由Program2读取为输入时。我尝试在终端中管道可执行文件(如下所示),但无法正常工作。
./Program1 | ./Program2
./Program1 |xargs ./Program2
./Program1 > ./Program2
Run Code Online (Sandbox Code Playgroud)
我想避免文件I / O。
注意: 平台:Linux
==================
遵循以下示例的内容
程序1(写到终端)
int main(int argc, char *argv[])
{
int i = 2200;
while(1){
printf("%d \n", i);
i++;
}
}
Run Code Online (Sandbox Code Playgroud)
程序2(从终端读取,程序1的输出)
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;
}
Run Code Online (Sandbox Code Playgroud)
问题是您正在尝试读取程序参数。但是,当您从一个程序流向下一个程序时,第一个程序的输出将成为第二个程序的标准输入(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';
}
}
Run Code Online (Sandbox Code Playgroud)