Supporting Piping (A Useful Hello World) Supporting Piping (A Useful Hello World) unix unix

Supporting Piping (A Useful Hello World)


Perhaps the problem is here:

if (numbers.size() > 0)

If you have any arguments, it adds them and ignores all piped data. So of course ./add 3 returns 3 - it has an argument, so it ignores the piped data.

You should fix your code to add both input (if input is given) and the arguments, not either-or. Remember: Command line arguments doesn't preclude piped input.


One function you might find useful is isatty(), which tells you whether a file descriptor is connected to an interactive session or not. You might use it like this:

if (!isatty(fileno(stdin))) {    while (std::cin) {        // ...    }}

This will only try to read input from the terminal if it's not interactive (meaning stdin is redirected from a file or pipe).


I would say the easiest is to ignore reading from stdin in your program. Instead, only let the program read from arguments, and call it like this: ./add 1 2 | xargs ./add 3 4

xargs will make the output from the first add an argument to the second add.