如何接受char或string作为输入

时间:2016-12-20 03:59:17

标签: c argp

在阅读了一篇关于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并不涵盖那些文档。

我开始学习C,我以基本的方式了解它,我对其他语言比较熟悉,所以为了更多地了解它,我想归档这个,但我不知道它怎么能让它接受一个char数组。

将arg与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

提前致谢。

1 个答案:

答案 0 :(得分: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);
}