我知道这个话题已经被打死了,但我仍然找不到我要找的东西。我需要在 C++ 中解析命令行参数。
我不能使用 Boost 和 long_getopt
问题在于铸造,当我简单地打印 arguments 时,它在循环中按预期工作,但分配给变量的值无法以某种方式工作。
这是完整的、可编译的程序。
#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++ 的新手,但非常努力地学习它 :)