2015-11-04 83 views
-1

我使用這個代碼:處理參數++不工作

int handleArgs(int argc, char *argv[]) { 

    if(argc <= 1) 
     {return 0;} 
    else 
     { // If no arguments, terminate, otherwise: handle args 

     for(int i=1; i<argc; i++) { 

      if (argv[i] == "-a" || argv[i] == "--admin") 
      {   // If admin argument 
       char *pwd = argv[i+1];   // i + 1 b/c we want the next argument; the password 

       if(pwd == "1729" || pwd == "GabeN") 
       {     // Verify Password 

       cout << "Sorry, console feature unavailable.\n" << endl;// Will replace with console function when I get to it 

       } 
       else 
       { 
        cout << "Wrong/No passkey, bruh.\n" << endl; 
       }  // If the password is wrong 


      } 
      else if (argv[i] == "-v" || argv[i] == "--version") 
      {  // If user asks for version info 

      cout << "You are running\nDev0.0.0" << endl;   // Tell the user the version 


      } 
      else if (argv[i]==" -h" || argv[i]=="--help") 
       { 

       cout << "Usage: " << argv[0] << " -[switch] argument(s)\n"; 
       cout << " -a, --admin  Open console view. Requires password\n"; 
       cout << " -v, --version  Print version and exit\n"; 
       cout << " -h, --help   Print this message and exit\n" << endl; 

       } 
       else { 
       cout << "Is you dumb?\n '" << argv[0] << " --help' for help" << endl;  // Insult the user 
        }      
     } 
    } 
    return 1; 
    } 

然而,每次我給它一個說法,我收到無效的參數消息(最後else語句):

Is you dumb? 
    'main --help' for help 

我是C++的新手,我不知道我在做什麼(錯誤)。任何人都可以提供一些有用的見解嗎?感謝

--FracturedCode

+0

你能告訴我你是如何傳遞參數...僅供參考.. –

+0

@MGP int main(int argc,char * argv []) – Gabe

+0

@MGP handleArgs(argc,argv); – Gabe

回答

3
argv

是C-字符串(char*)的陣列。您正在使用==並比較內存地址,而不是C++字符串提供的超載==運算符。您應該使用strncmp來比較您的字符串(它比strcmp更安全)。雖然在這裏並不重要,因爲你正在比較文字,這可以保證其中一個會結束。