3

このトピックが打ちのめされたことは知っていますが、探しているものが見つかりませんでした。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++ を初めて使用しますが、それを学ぼうと一生懸命努力しています :)

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 に答える