管道和命令行参数 [英] Piping and Command Line arguments

查看:162
本文介绍了管道和命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题已解决,代码重写如下:

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;
}

除了一点点,CMD和Powershell的输出在视觉上是不同的-在Powershell中执行此操作时,看起来好像有两个结尾行(也就是说,每条适当的行之间都有一个空白行),我怀疑(但尚未调查)这是因为结尾处有很多空白的Powershell行,因此当您在前面添加 xx的xx是 时,该行会回绕。

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.

=================================================== ==

此代码应仅打印所有参数:

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

输出符合预期:

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

我得到的输出是:

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

仅此而已。

这不是因为 dir 和/或 ls 返回没什么-不用管道就单独调用这些命令可以像往常一样给我文件结构。我怀疑我缺少必要的内容-可能与管道行为有关-但对于应该从哪里开始我一无所知。

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.

推荐答案

管道不适用于参数,而是标准输入。

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

如果您想读取 ls 发送的数据dir 到您的程序,您需要阅读一个流: std :: cin

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

一个基本的C ++示例:此处

A basic C++ example : here.

这篇关于管道和命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆