繁体   English   中英

管道和命令行参数

[英]Piping and Command Line arguments

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

#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 of xx is "时,该行会回绕。

==================== ORIGINAL = QUESTION = BENEATH = THIS =行====================

此代码应仅显示所有参数:

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

它似乎运行良好-如果我打电话给例如

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

但是当我这样做时,在命令行中:

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返回任何内容-单独调用这些命令而不进行管道传输会照常给我文件结构。 我怀疑我缺少一些必不可少的内容-可能是关于管道行为的信息-但对于应该从哪里开始我一无所知。

管道将stdin传递给命令,而不是命令行参数。 您需要使用stdin读取“管道”。

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

如果要读取由lsdir发送到程序的数据,则需要读取stream: std :: cin

一个基本的C ++示例: 在这里

您使用命令行处理器-这是用户命令的相当复杂的解释器。 因此,该解释器具有一组规则-一些规则描述了如何启动程序,但是一些规则修改了命令行处理器的行为。 | &><是用于解释程序的命令,但不适用于您的程序。 这就是为什么它不被视为命令行参数的原因。 但是你可以通过| 借助引号:

myprog "arg1 | arg2" 

但在这种情况下,它不是流的管道

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM