tags:

views:

96

answers:

3

Hello, I would like to fill my vector<float> from command line:

more my.txt | myexe.x > result.txt

What is the best way to open the pipe in C++? Thanks Arman.

+10  A: 

Your shell will connect the standard output of more to the standard input of myexe.x. So you can just read from std::cin, and need not worry whether the input comes from the keyboard or from some other program.

For example:

vector<float> myVec;
copy(istream_iterator<float>(cin), istream_iterator<float>(),
     back_inserter(myVec));
Thomas
@Thomas: Thanks Tomas, but what about end of the inputs? should I check in the end EOF? or what?
Arman
@arman - istream_iterator<float>() represents end of input.
Noah Roberts
+2  A: 

That particular pipe is attached to your app's stdin, so you can just read from there.

pdbartlett
+3  A: 

You can do that with std::copy() from <algorithm>, but you don't need that extra dependency.

#include<iterator>

// ...
std::vector<float> them_numbers(std::istream_iterator<float>(std::cin),
                                std::istream_iterator<float>());

If you know beforehand exactly how many values you expect, then you can avoid the reallocations:

std::vector<float>::size_type all_of_them /* = ... */;
std::vector<float> them_numbers(all_of_them);
them_numbers.assign(std::istream_iterator<float>(std::cin),
                    std::istream_iterator<float>());
wilhelmtell
thanks, good to notice.
Arman