pipe C++

Hello!

I have written a program that successfully reads certain lines from a file, and then does something with the this data. But, I want to use pipes in linux to accomplish the same task. In order words:

cat file | ./myProgram

I have tried to google this, but I didn't find anything useful. Thanks in advance!
From the above example I'm guessing you want the information from file to pipe to the created myProgram not even sure if that is possible. ...."THINKING" a pipe takes output from the previous to the next so..

why not create your program to use the file you input as an argument and work on piping it in the app using scripting. you not limited but be careful.
Last edited on
Just make your program read from cin

Then the pipe command shown will work fine

Also if your program writes to cout then you can pipe its output to something else if needed

If you want your program to print something to the terminal while its doing its stuff then write that to cerr

Simple.
What mik2718 said.
std::cin is Standard Input (named stdin in C)
std::cout is Standard Output (stdout in C)
std::cerr is Standard Error (stderr in C)

The pipe command in the shell | simply links the first program's output with the next program's input.

Here's a reference that may prove useful, although it's for C, not C++:
http://www.cs.cf.ac.uk/Dave/C/
Thanks for the help guys! It sounds easy, but I still can't seem to get it :) I tried this:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>

int main()
{
    string input;
    std::cin >> input;

    ...do something...
}


But! It seems like only the first word of stdout is stored in the string-array. Help me please :)
It may help to think of the >> operator as a single-fire mechanism for extracting data, which stops when it encounters the first whitespace.

You can prevent this in a number of ways:

1) use the noskipws() manipulator function thing
http://www.cplusplus.com/reference/iostream/manipulators/noskipws/
My bad.

2) use getline(istream&, string&)
http://www.cplusplus.com/reference/string/getline/

3) or (and this is handy if the input data is binary) remember std::cin is just a file, and treat it as such:
http://cplusplus.com/reference/iostream/istream/read/

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <vector>

int main()
{
    std::vector<char> someData(10, '-'); // roughly same as char someData[10] = "---------";

    std::cin.read(&someData.front(), someData.size());
    someData.back() = '\0'; // NIL-terminated, so that it's known where it ends
    std::cout << someData.data() << std::endl;
}

Last edited on
Thank you so much! :) Finally got it.
Topic archived. No new replies allowed.