[英]Getopt doesn't seem to recognise arguments
我在 C++ 開始一個新項目,我首先創建一個 function,它使用 getopt 處理命令行 arguments,但它似乎不起作用。 恐怕這是一個小錯誤,但我已經調試了一段時間的代碼,但我仍然不明白為什么它不起作用。 問題是,在運行程序時,當我使用這些標志運行程序時,它不會進入任何切換情況。
這是代碼:
bool verbose = false;
void commandlinearguments (int argc, char** argv, char** word_file_name, char** GSport) {
int opt;
sprintf(*GSport, "%d", 58000+GN);
while ( opt = getopt(argc, argv, "p:v") != -1 ) {
switch (opt) {
case 'p':
cout << optarg << endl;
*GSport = optarg;
break;
case 'v':
verbose = true;
break;
}
}
if ( argv[optind] != NULL ) {
*word_file_name = argv[optind];
} else {
cout << "Word file not specified. Aborting." << endl;
exit(1);
}
return;
}
int main (int argc, char** argv) {
char* GSport = new char[6];
char* word_file_name = NULL;
commandlinearguments(argc, argv, &word_file_name, &GSport);
cout << word_file_name <<endl;
cout << GSport << endl;
cout << verbose << endl;
return 0;
}
我正在這樣編譯:
g++ server.cpp -o gs -g
當我運行./gs wf -p 12345 -v
時,output 是:
wf
58003
0
任何人都可以看到我做錯了什么?
opt = getopt(argc, argv, "p:v") != -1
是相同的
opt = (getopt(argc, argv, "p:v") != -1)
所以opt
是 0 還是 1 取決於結果是否為 -1。 你可能是說
(opt = getopt(argc, argv, "p:v")) != -1
它將結果分配給opt
然后檢查它是否為 -1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.