c - 如何接受字符或字符串作为输入

标签 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,我对它有一个基本的了解,我对其他语言比较熟悉,所以要了解更多关于它的信息我想存档这个但我不明白我怎么能做到接受一个字符数组。

将 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

提前致谢。

最佳答案

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);
}

关于c - 如何接受字符或字符串作为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41234683/

相关文章:

c - libc 中的静态内联函数

c - 打开()一个文件并在最后写入

c - 使用 appsrc 通过 gstreamer udpsink 进行流式传输

c - argp 和 getopt 有什么区别?

C - 如何允许 Argp 或 Getopt 中无法识别的选项?

c - C 中与 argp 互斥的选项

c - 如果使用函数,编译器会发出警告

c - 使用 fread 从文件读取数据到结构

c - 带/不带选项的 getopt 用法