2012-11-28 41 views
3

在輸入選項/參數後,如何使用使用argv []的if/then語句?使用if/then語句解析C++中的argv []選項

例如,的a.out -d 1 sample.txt的的a.out -e 1 sample.txt的

int main (int argc, char *argv[]) 
{ 
    ifstream infile(argv[3]); 

    int c; 
    int number = 0; 
    int count = 0; 

    while (infile.good()) { 

      if (argv[1] == "-d") 
      { 

       c = infile.get(); 

       number = atoi(argv[2]); 

        if (number == count) 
       { 
       cout.put(c); 
       count = 0; 
       } 

         else 
         count++; 

      }  


      if (argv[1] == "-e") 
      { 
       cout << "entered -e" << endl; //testing code 
      } 


    }//end while 

}//end main 
+0

可能的重複http://stackoverflow.com/questions/11106062/are-command-line-arguments-some-strings – chill

+0

你的代碼是否給出錯誤? – asheeshr

+0

你能否重申你的問題?你的問題到底是什麼? –

回答

2

不能使用等於運算符來比較C風格的字符串,你必須使用std::strcmp

if (std::strcmp(argv[1], "-d") == 0) 

背後的原因是==運營商指針比較不他們指的是什麼。

+0

這開始具有一定意義。它仍然沒有做任何事.. – harman2012

0

焦炭的argv []是字符數組* 所以

if (string(argv[1]) == "-d") 
1

我希望你要檢查的輸入參數-d-e,對不對? 如果是這樣的話,請使用的strcmp()

如果(的strcmp(argv的[1], 「! - d」)) {

  count++; 
      printf("\ncount=%d",count); 

     }  

     if (!strcmp(argv[1],"-e")) 
     { 
      printf("entered -e"); //testing code 
     } 
1

第一個錯誤是在的第一行main

ifstream infile(argv[3]); 

你不能寫,因爲沒有第三個參數。當你調用你的程序是這樣的:

a.out -d 1 < sample.txt 

然後該程序看到的命令行看起來是這樣的:

argv[0] = "a.out" 
argv[1] = "-d" 
argv[2] = "1" 

< sample.txt,相反,是由shell解釋直接和文件將流式傳輸到您的程序的標準輸入 - 並且您無法在您的程序中改變這一點。

至於解析本身,不要這樣做裏面的讀取文件的循環,之前做它並設置適當的標誌。

對於實際的解析我建議使用庫來免除你很多的痛苦。標準的Unix工具是getopt,但只有C接口。有幾個C++庫,其中Boost.Program_Options這對我來說太複雜了。

+0

謝謝大家!我不得不將它改爲字符串比較,當我改變了一些東西時,strcmp不起作用。 – harman2012

1

的ARGC/argv的來自C和是相當麻煩的使用,所以當比基本參數傳遞更多的是做,你可以改變參數字符串的載體和工作在一個C++風格:

#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <iterator> 

main(int argc, char* argv[]) 
{ 
    std::vector<std::string> args; 
    std::transform(argv+1, argv+argc, std::back_inserter(args), [](char* arg){ return std::string(arg); }); 

    if (args.at(1) == "-d") { std::cout << "Arg 1 = -d" << "\n"; } 

    for (auto& arg: args) { std::cout << "arg: " << arg << "\n"; } 
} 

不過,您需要檢查參數是否存在。如果這是一個基本的工具,它是可以接受的,該工具中止時的參數不存在,那麼你就可以訪問ARGS元素與args.at(x)代替args[x]

或檢查this SO question的參數解析器。