3

我知道这个话题已经被打死了,但我仍然找不到我要找的东西。我需要在 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++ 的新手,但非常努力地学习它 :)

4

2 回答 2

4

您正在将字符串 (char*) 值转换为整数值,这与解析它非常不同。通过强制转换,您将第一个字符的 ASCII 值用作数值,而通过解析字符串,您尝试将整个字符串解释为文本并将其转换为机器可读的值格式。

您需要使用解析函数,例如:

std::stringstream argument(optarg);
argument >> iterations;

或者

boost::lexical_cast<int>(optarg);

或(C 风格)

atoi(optarg)
于 2011-09-17T10:59:47.303 回答
0

因为 optarg 是 char*。是纯文本。所以如果你给你的程序 .8 作为参数,那么 optarg 是一个字符串 ".8" 并且将它转换为 float 是行不通的。例如,使用 atoi 和 atof 函数(在“stdlib.h”中声明)将字符串解析为 int 和 float。在您的代码中,它将是:

iterations = atoi(optarg);
decay = atof(optarg);
于 2011-09-17T11:05:21.673 回答