2016-12-20 7 views
1

として、文字または文字列を受け入れるように、私はそれで何かを作りたかったのですが、私はこの例では、問題を抱えている:どうargpはおよそ有名なPDFファイルを読んだ後、入力

static int parse_opt (int key, char *arg, struct argp_state *state) 
{ 
    switch (key) 
    { 
     case 'd': 
     { 
      unsigned int i; 
      for (i = 0; i < atoi (arg); i++) 
       printf ("."); 
      printf ("\n"); 
      break; 
     } 
    } 
    return 0; 
} 

int main (int argc, char **argv) 
{ 
    struct argp_option options[] = 
    { 
     { "dot", 'd', "NUM", 0, "Show some dots on the screen"}, 
     { 0 } 
    }; 
    struct argp argp = { options, parse_opt, 0, 0 }; 
    return argp_parse (&argp, argc, argv, 0, 0, 0); 
} 

-d int型の引数を受け取りますが、引数としてcharまたはchar配列を取得したいのですか? pdfはそのドキュメントをカバーしていません。

私は基本的な方法でそれを知っています。私は他の言語で詳しく知っていますので、もっと詳しく知りたいのですが、これをアーカイブしたいのですが、どうすればいいですか? char配列を受け取ります。文字と引数を比較するときに動作しませんでした

コード:事前に

static int parse_opt(int key, char *arg, struct argp_state *state) 
{  
    switch(key) 
    { 
     case 'e': 
     { 
      //Here I want to check if "TOPIC" has something, in this case, a char array 
      //then based on that, do something. 
      if (0 == strcmp(arg, 'e')) 
      { 
       printf("Worked"); 
      } 
     } 
    } 

    return 0; 
}//End of parse_opt 

int main(int argc, char **argv) 
{ 
    struct argp_option options[] = 
    { 
     {"example", 'e', "TOPIC", 0, "Shows examples about a mathematical topic"}, 
     {0} 
    }; 

    struct argp argp = {options, parse_opt}; 

    return argp_parse (&argp, argc, argv, 0, 0, 0); 
}//End of main 

感謝。

+0

マインド '-dは'、int型の引数を受け入れ明確化? – sjsam

+2

"-dはint型の引数を受け取ります"。それは真実ではない。 'arg'は常に文字列です。それを 'int'に変更するのはあなたのコードです。文字列として保存したい場合は 'atoi'を呼び出さないでください。 – kaylum

+0

@sjsam確かに、 "NUM"との関係を持つiという符号なしintがあります。-dの引数、 "NUM"引数justsは整数を受け取り、charまたはchar配列を受け入れたいと思います。 –

答えて

1

https://www.gnu.org/software/libc/manual/html_node/Argp.html

#include <stdio.h> 
#include <argp.h> 
#include <string.h> 

static int parse_opt(int key, char *arg, struct argp_state *state) { 
    (void)state; // We don't use state 
    switch (key) { 
    case 'c': { 
    if (strlen(arg) == 1) { // we only want one char 
     char c = *arg;  // or arg[0] 
     printf("my super char %c !!!\n", c); 
    } else { 
     return 1; 
    } 
    } 
    } 
    return 0; 
} 

int main(int argc, char **argv) { 
    struct argp_option const options[] = { 
     {"char", 'c', "c", 0, "a super char", 0}, {0}}; 
    struct argp const argp = {options, &parse_opt, NULL, NULL, NULL, NULL, NULL}; 
    argp_parse(&argp, argc, argv, 0, NULL, NULL); 
} 
+0

私はちょっとそれを取得しますが、NULLと言うときstruct argpドキュメントの例では、少なくとも私が見ている例のようなものは表示されません。 –

+0

'struct argp'には多くのフィールド[doc](https://www.gnu.org/software/libc/manual/html_node/Argp-Parsers.html#Argp-Parsers)があるので、警告にするだけです。 'NULL'が何であるかを知るには[this](http://stackoverflow.com/questions/1296843/what-is-the-difference-between-null-0-and-0) – Stargateur

+0

それは仕事をしました、ありがとう –

関連する問題