Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Piping and Command Line arguments

Tags:

c++

windows

cmd

The problem has been solved, the code re-write is as follows:

#include <iostream>
#include <string>
#include <vector>

int main(int argc, char** argv){

    std::string input;
    std::vector<std::string> inputVector;

    while(std::getline( std::cin, input ) ){

        inputVector.push_back(input);
    }

    for(int i = 0; i < inputVector.size(); i++){

        std::cout << i << " of " << inputVector.size()-1 << " is " << inputVector[i] << "\n";

    }

    return 0;
}

As a slight aside, the output is different in CMD and in Powershell visually - it looks like there are TWO endlines when this is done in Powershell (That is, there is a blank line between each proper line) and I suspect (but have not investigated) that this is because there is a whole lot of whitespace at the end of Powershell lines so when you prepend "xx of xx is " at the front, the line wraps around.

====================ORIGINAL=QUESTION=BENEATH=THIS=LINE====================

This code should just print all arguments:

//dirparser.cpp
#include <iostream>

int main(int argc, char** argv){

    for( int i = 0; i<argc ; i++){

        std::cout << i << " of " << argc-1 << " is " << argv[i] << "\n";
    }

    return 0;
}

And it seems to run fine - if I call e.g

dirparser.exe a b c

The output is as expected:

0 of 3 is dirparser.exe
1 of 3 is a
2 of 3 is b
3 of 3 is c

But when I do this, in the command line:

dir | dirparser.exe   //In CMD
dir | .\dirparser.exe //In Powershell
ls | .\dirparser.exe  //In Powershell

The output I get is:

0 of 0 is dirparser.exe              //CMD
0 of 0 is [directory]\dirparser.exe  //Powershell
0 of 0 is [directory]\dirparser.exe  //Powershell

And nothing further.

It's not because dir and/or ls return nothing - calling those commands alone without piping gives me the file structure as per usual. I suspect I'm missing something essential - probably about piping behavior - but I'm fairly clueless as to where I should start.

like image 332
shieldfoss Avatar asked Mar 15 '26 17:03

shieldfoss


1 Answers

Piping doesn't work with arguments, but standard input.

If you want to read the data send by ls or dir to your program, you need to read a stream : std::cin.

A basic C++ example : here.

like image 180
Louis Brunner Avatar answered Mar 18 '26 06:03

Louis Brunner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!