在阅读了著名的关于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
提前谢谢。
最佳答案
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/