[英]Splitting and accessing strings in C
我是C语言的新手,正在尝试将参数传递给程序,例如
program_name -param1=something -param2=somethingelse
然后在我的程序中,我想循环遍历参数,并在“ =”上将其拆分,然后将这两部分打印回命令行。 这是我到目前为止的
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i = 0;
char parampart;
char paramvalue;
for(i = 0; i < argc; i++)
{
parampart = strtok(argv[i], "=");
paramvalue = strtok(NULL, "=");
printf("parampart: %s paramvalue %s", parampart, paramvalue);
}
return 0;
}
我收到错误消息是因为变量parampart和paramvalues是指针,但是我不确定如何使用指针来获取字符串值。
如果您使用的是Linux,则可以使用getopt 。 它使生活更轻松
strtok()
返回指针,因此您必须将parampart
和paramvalue
声明为指针,例如
char *parampart;
char *paramvalue;
您其余的代码是正确的。
问题是您假设每个参数中都将有一个=
。 他们大多数人都在做...。但不是第零个,即program_name
。 您应该从参数1开始,而不是参数0,并且应该检查第二次strtok
调用是否返回空值,以防用户忘记了等号。
当然,正如@MOHAMED所述,这是getopt的工作。
这是man strtok
的一个很好的例子,您应该在循环之后调用一次:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char *argv[])
{
char *str1, *str2, *token, *subtoken;
char *saveptr1, *saveptr2;
int j;
if (argc != 4) {
fprintf(stderr, "Usage: %s string delim subdelim\n",
argv[0]);
exit(EXIT_FAILURE);
}
for (j = 1, str1 = argv[1]; ; j++, str1 = NULL) {
token = strtok_r(str1, argv[2], &saveptr1);
if (token == NULL)
break;
printf("%d: %s\n", j, token);
for (str2 = token; ; str2 = NULL) {
subtoken = strtok_r(str2, argv[3], &saveptr2);
if (subtoken == NULL)
break;
printf(" --> %s\n", subtoken);
}
}
exit(EXIT_SUCCESS);
}
根据man getopt
说法:
#include <stdio.h> /* for printf */
#include <stdlib.h> /* for exit */
#include <getopt.h>
int
main(int argc, char **argv)
{
int c;
int digit_optind = 0;
while (1) {
int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] = {
{"add", required_argument, 0, 0 },
{"append", no_argument, 0, 0 },
{"delete", required_argument, 0, 0 },
{"verbose", no_argument, 0, 0 },
{"create", required_argument, 0, 'c'},
{"file", required_argument, 0, 0 },
{0, 0, 0, 0 }
};
c = getopt_long(argc, argv, "abc:d:012",
long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 0:
printf("option %s", long_options[option_index].name);
if (optarg)
printf(" with arg %s", optarg);
printf("\n");
break;
case '0':
case '1':
case '2':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf("option %c\n", c);
break;
case 'a':
printf("option a\n");
break;
case 'b':
printf("option b\n");
break;
case 'c':
printf("option c with value '%s'\n", optarg);
break;
case 'd':
printf("option d with value '%s'\n", optarg);
break;
case '?':
break;
default:
printf("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc) {
printf("non-option ARGV-elements: ");
while (optind < argc)
printf("%s ", argv[optind++]);
printf("\n");
}
exit(EXIT_SUCCESS);
}
我建议您为每个选项设置标志,并根据程序的行为将其初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.