このトピックが打ちのめされたことは知っていますが、探しているものが見つかりませんでした。C++ でコマンド ライン引数を解析する必要があります。
Boost と long_getopt を使用できません
問題はキャストにあります。単に引数を出力すると、ループで期待どおりに機能しますが、変数に割り当てられた値が何らかの形で機能しません。
コンパイル可能な完全なプログラムを次に示します。
#include <iostream>
#include <getopt.h>
using namespace std;
int main(int argc, char *argv[])
{
int c;
int iterations = 0;
float decay = 0.0f;
int option_index = 0;
static struct option long_options[] =
{
{"decay", required_argument, 0, 'd'},
{"iteration_num", required_argument, 0, 'i'},
{0, 0, 0, 0}
};
while ((c = getopt_long (argc, argv, "d:i:",
long_options, &option_index) ) !=-1)
{
/* getopt_long stores the option index here. */
switch (c)
{
case 'i':
//I think issue is here, but how do I typecast properly?
// especially when my other argument will be a float
iterations = static_cast<int>(*optarg);
cout<<endl<<"option -i value "<< optarg;
break;
case 'd':
decay = static_cast<float>(*optarg);
cout<<endl<<"option -d with value "<<optarg;
break;
}
}//end while
cout << endl<<"Value from variables, which is different/not-expected";
cout << endl<< decay << endl << iterations << endl;
return(0);
}
コメントで述べたように、問題は型キャストにあると思いますが、適切に行うにはどうすればよいですか? 他に良い方法があれば教えてください。
--- ./program-name -d .8 -i 100 としてプログラムを実行できます
ご協力ありがとうございました。私は Unix と C++ を初めて使用しますが、それを学ぼうと一生懸命努力しています :)