简体   繁体   English

在C中分割和存取字串

[英]Splitting and accessing strings in C

I am new to C and I am trying to pass arguments to my program like 我是C语言的新手,正在尝试将参数传递给程序,例如

program_name -param1=something -param2=somethingelse

Then in my program I want to loop through the arguments and split them on the "=" and print the two parts back to the command line. 然后在我的程序中,我想循环遍历参数,并在“ =”上将其拆分,然后将这两部分打印回命令行。 Here is what I have so far 这是我到目前为止的

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

I am getting errors because the variables parampart and paramvalues are pointers but I'm not sure how to use the pointers to get the string values. 我收到错误消息是因为变量parampart和paramvalues是指针,但是我不确定如何使用指针来获取字符串值。

If you are using Linux you can use getopt . 如果您使用的是Linux,则可以使用getopt it make life easier 它使生活更轻松

The strtok() returns pointer, so you have to declare parampart and paramvalue as pointers, like strtok()返回指针,因此您必须将parampartparamvalue声明为指针,例如

char *parampart;
char *paramvalue;

the rest of your code is correct. 您其余的代码是正确的。

The problem is that you're assuming each argument will have a = in it. 问题是您假设每个参数中都将有一个= Which most of them do.... but not the zero'th one, which is program_name . 他们大多数人都在做...。但不是第零个,即program_name You should start at arg 1, not arg 0, and you should check for a null return from the second strtok call, in case the user forgets the equals-sign. 您应该从参数1开始,而不是参数0,并且应该检查第二次strtok调用是否返回空值,以防用户忘记了等号。

Of course, as @MOHAMED mentioned, this is a job for getopt. 当然,正如@MOHAMED所述,这是getopt的工作。

It's a good example from man strtok , you should call once befroe your loop: 这是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);
   }

And according to man getopt : 根据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);
}

I suggest you set flag for each option and initilize them according to behave your program. 我建议您为每个选项设置标志,并根据程序的行为将其初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM