我知道这个话题已经被打死了,但我仍然找不到我正在寻找的东西。我需要在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++的新手,但是非常努力地学习它:)
发布于 2011-09-17 18:59:47
您将字符串(char*)值转换为整数值,这与解析它有很大的不同。通过强制转换,您使用第一个字符的ASCII值作为数值,而通过解析字符串,您尝试将整个字符串解释为文本,并将其转换为机器可读的值格式。
您需要使用如下解析函数:
std::stringstream argument(optarg);
argument >> iterations;或
boost::lexical_cast<int>(optarg);或(C样式)
atoi(optarg)发布于 2011-09-17 19:05:22
因为optarg是char*。这是纯文本。因此,如果你给你的程序.8作为参数,那么optarg是一个字符串".8“,并且将它转换为float是不起作用的。例如,使用atoi和atof函数(在‘stdlib.h’中声明)将字符串解析为int和float。在你的代码中,它应该是:
iterations = atoi(optarg);
decay = atof(optarg);https://stackoverflow.com/questions/7454238
复制相似问题