How can I draw the output of one program and use it as the input of another in C ++?

I have a program that takes into account the number of experiments as a command line argument and outputs a sequence of floating numbers. Example: im_7.exe 10 10.41 13.33 8.806 14.95 15.55 13.88 10.13 12.22 9.09 10.45

So, I need to call this program in my program and analyze this sequence of numbers.

+4
source share
3 answers

If you are in windows, you need to do the following

  • Create Pipe1 using the CreatePipe api for windows. Use this channel to read data from the STDOUT child process.
  • Create Pipe2 in the same way and use this pipe to write data to the STDIN of the child process.
  • Create a child process and in the startup information specify these descriptors and inherit the descriptors of the parent process. Also pass the arguments to the cmd string.
  • Close the end of the Pipe1 entry and read the end of Pipe2.
  • In your case, you are not writing anything to the input of the child process. You can immediately read the data from the output process by reading from Pipe1.

For example, consider the following link. http://msdn.microsoft.com/en-us/library/ms682499%28VS.85%29.aspx

Hope this is what you are looking for.

+4
source

Data that one program outputs to standard output ( std::cout in C ++) can be sent to standard input ( std::cin ) of another program. The specifics of connecting two programs depends on the environment (in particular, the operating system and the shell).

+4
source

You can create a class containing your data (with overloads >> and << )

 include <iostream> #include <iterator> #include <vector> class MyData { public: friend std::istream& operator>>(std::istream& in, MyData& data) { in >> data.size ; data.m_data.resize(data.size); std::copy( std::istream_iterator<float>(in), std::istream_iterator<float>( ), data.m_data.begin() ); } friend std::ostream& operator<<(std::ostream& out, MyData& data) { out<< data.size << " "; for(size_t i=0;i<data.size;++i){ out<< data.m_data[i] <<" "; } return out; } private: int size; std::vector<float> m_data; }; 

And then you can call him that

 int main (int ac, char **av) { MyData d; std::cin>>d; //input one set of data; //test std::cout<<d; //get multiple data files std::vector<MyData> buffer; std::copy( std::istream_iterator<MyData>(std::cin), std::istream_iterator<MyData>( ), std::back_inserter(buffer)); // copies all data into buffer } 

On Linux, a test tube can be formed as follows:

 echo "4 1.1 2.2 3.3 4.4" | ./a.out 

Not sure how to make pipes in windows though ...

+2
source

All Articles