Piping and Command Line arguments

2019-04-12 19:44发布

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.

标签: c++ windows cmd
3条回答
爷、活的狠高调
2楼-- · 2019-04-12 20:14

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.

查看更多
Animai°情兽
3楼-- · 2019-04-12 20:17

Piping passes stdin to the command, not command line arguments. You need to read off the 'pipe' using stdin.

查看更多
做自己的国王
4楼-- · 2019-04-12 20:29

You use command line processor - that is rather complicated interpreter of user command. So this interpreter has set of rules - some rules describe how to start your program but some rules modifies behavior of command line processor. |, &, >, < are commands for interpreter but not for your program. That is why it is not treated as command line arguments. But you can pass | with help of quotes:

myprog "arg1 | arg2" 

But in this case it is not pipe of streams

查看更多
登录 后发表回答