簡體   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