Search code examples
cscanf

sscanf: how to parse


I'm trying to parse this string:

+CGDCONT: 0,"IP","free","10.158.88.34"

In bold are the items i'm interested in. My first attempt was to use this pattern:

"+CGDCONT: %d,\"IP\",\"%*s\",\"%d.%d.%d.%d\""

with it, only 1 variable is parsed.

Then, I tried:

"+CGDCONT: %d,\"IP\",\"free\",\"%d.%d.%d.%d\"  // the string "free" is hard coded

It works but "free" might not be always "free", so I need a way to ignore it.

Then, I tried:

"+CGDCONT: %d,\"IP\",\"%s\",\"%d.%d.%d.%d\"  // the string "free" is no more optionnal

with it, 2 variables are parsed. The second one (%s) is parsed as

free","10.158.88.34"\8  // \8 is ascii char 8.

How should I do?


Solution

  • If you want, effectively, a one-liner you can do it like this:

    #include <stdio.h>
    
    int main(void) {
        char inp[] = "+CGDCONT: 0,\"IP\",\"free\",\"10.158.88.34\"";
        int val = -1;
        int arr[4] = { -1, -1, -1, -1 };
        printf("Processing %s\n", inp);
    
        if(sscanf(inp, " +CGDCONT: %d ,\"IP\", %*[^,], \" %d.%d.%d.%d\"",
                &val, &arr[0], &arr[1], &arr[2], &arr[3]) != 5)
            return 1; // handle error
    
        printf("val = %d, arr[] = %d %d %d %d\n", val, arr[0], arr[1], arr[2], arr[3]);
    }
    

    The first substring is matched before the bolded 0 or other int, which is processed (the leading space is to filter previous newlines etc). The next substring is matched, the next is skipped using %*[]. Then the comma and quote are matched, followed by the four dot-separated int values.

    Program output:

    Processing +CGDCONT: 0,"IP","free","10.158.88.34"
    val = 0, arr[] = 10 158 88 34