2012-05-08 46 views
1

錯誤,同時從http://code.google.com/p/darungrim/source/browse/trunk/ExtLib/XGetopt.cpp?r=17如何調用正確的getopt函數

`check.cpp: In function ‘int main()’:` 

check.cpp:14:55: error: invalid conversion from ‘const char**’ to ‘char* const*’ [-fpermissive]

/usr/include/getopt.h:152:12: error: initializing argument 2 of ‘int getopt(int, char* const*, const char*)’ [-fpermissive]

#include <iostream> 
#include <cstring> 
#include <string> 
#ifdef USE_UNISTD 
#include <unistd.h> 
#else 
#include "XGetopt.h" 
#endif 
using namespace std; 

int main() { 

string text="-f input.gmn -output.jpg"; 
int argc=text.length(); 
cout<<"argc: "<<argc<<endl; 
char const * argv = text.c_str(); 
cout<<"argv: "<<argv<<endl; 
int c = getopt (argc, &argv, "f:s:o:pw:h:z:t:d:a:b:?"); 
cout<<"c: "<<c<<endl; 
return 0; 
} 

回答

5

調用INT getopt的功能您在這裏失蹤兩件事情:

  1. 參數列表不是字符串。它是一個字符串列表。不要被shell或其他程序混淆,要求將參數列表作爲單個字符串。在一天結束時,這些程序會將字符串拆分爲參數數組並運行可執行文件(例如,參見execv)。
  2. 參數列表中總是有一個隱含的第一個參數,它是一個程序名。

這裏是你的代碼,固定:

#include <string> 
#include <iostream> 
#include <unistd.h> 

int main() 
{ 
    const char *argv[] = { "ProgramNameHere", 
          "-f", "input.gmn", "-output.jpg" }; 
    int argc = sizeof(argv)/sizeof(argv[0]); 
    std::cout << "argc: " << argc << std::endl; 
    for (int i = 0; i < argc; ++i) 
     std::cout << "argv: "<< argv[i] << std::endl; 
    int c; 

    while ((c = getopt(argc, (char **)argv, "f:s:o:pw:h:z:t:d:a:b:?")) != -1) { 
     std::cout << "Option: " << (char)c; 
     if (optarg) 
      std::cout << ", argument: " << optarg; 
     std::cout << '\n'; 
    } 
} 
+0

非常感謝你的解決方案!我的問題是,我正在構建命令行工具,在開始時整行是一個字符串。如何將'string text =「 - f input.gmn -output.jpg」;'轉換爲'const char * argv [] = {「ProgramNameHere」, 「-f」,「input.gmn」,「-output .jpg「};' – strausionok

+0

@ user1020174:我建議你問一個單獨的問題,如何分割一個字符串。 – 2012-05-08 21:03:25

+0

哦,請簡單地回答「在getopt_long()中的'argv'參數參數之前插入那麼多需要的'(char **)'。 –