简体   繁体   中英

use of strsep in C while parsing argv Variable doesen't work

I have a problem in C while parsing the argv Variable. This is the task:

I got some Parameters form the Command line into my C programm. One of them looks like "-r=20-5". There I have to find the "r". this works with:

if (argv[i][0] != 0 && argv[i][1] != 0 && argv[i][2] != 0 &&
    argv[i][0] == '-' && argv[i][2] == '=') { /* Check the Variables */
    switch (argv[i][1]) {
        case 'r':
            /* what have to be here? */
            break;
}

Now I have the "r". But I need the 20 and the 5 in two different variables too. Here is what i thougt about, but it did't work. I tried something with

strsep(argv[i]+3, "-");

But my Compiler (Xcode) throws a warning (warning: passing argument 1 of 'strsep' from incompatible pointer type)

Does anyone has any idea (or link) how I can solve the problem?


After it's solved there was still a warning, so I was answered to post my entire new code:


int parse(int argc, const char *argv[]) {
    int i, x, y;
    int intTmp;
    long longTmp;
    char *strTmp;
    char *end;

    for (i = 1; i < argc; i++) {
        /* check for (-?=) */
        if (argv[i][0] != 0 && argv[i][1] != 0 && argv[i][2] != 0 &&
            argv[i][0] == '-' && argv[i][2] == '=') {

            /* IGNORE THIS
             * longTmp = strtol(argv[i]+3, &end, 10);
             * intTmp = analyseEndptr(longTmp, argv[i]+3, end);
             */

            switch (argv[i][1]) {
                case 'r':
                    strTmp = argv[i]+3;                 /* <= Here I got the warning */
                    x = atoi(strsep(&strTmp, "-"));
                    y = atoi(strsep(&strTmp, "-"));
                    printf("x=%d, y=%d\n", x, y);
                    break;
            }
        }
    }
}

The warning is: warning: passing argument 1 of 'strsep' from incompatible pointer type

My compiler is: gcc on MacOS using XCode as IDE

Do you know sscanf? Have a look at:

  unsigned a,b;
  if( 2==sscanf(argv[i],"-r=%u-%u",&a,&b) )
    printf("%u-%u",a,b);

Here is how you pass a string to strsep()

    switch (argv[i][1]) {
        char *s;
        int x, y;
        case 'r':
            s = argv[i] + 3;
            x = atoi(strsep(&s, "-"));
            y = atoi(strsep(&s, "-"));
            printf("x=%d, y=%d\n", x, y);
            break;
    }

Will produce:

x=3, y=4

Do not use it as is. You will have to do additional NULL checks on x and y appropriately for your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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