sscanf variable length string parsing

c, c++, parsing, string

Solution

Just parse the string in two (or more) passes. This uses the `%n` format specifier to write the number of bytes processed, so we know where to pick up in subsequent passes:

int a, b, n, pos;
const char *buf = "12 34 2 3 yes 2 no";

assert(sscanf(buf, "%d %d %d %n", &a, &b, &n, &pos) == 3);
for(int i=0; i<n; i++) {
    int cur;

    int x;
    char y[20];

    assert(sscanf(buf+pos, "%d %19s %n", &x, y, &cur) == 2);
    printf("%d %s\n", x, y);
    pos += cur;
}

outputs

3 yes
2 no

Problem

I have a problem that is probably fairly common and likely has a beautiful hack that I am not aware of. I would greatly appreciate it if someone would enlighten me! I am using C's sscanf() function to parse input and the format is "%d %d %d %s %d %s %d ..." where the first two %d are random ID integers (insignificant) for the string and the third is a count of the number of %d %s combinations to follow. For instance, "12 34 2 3 yes 2 no" could be a string, where 12 and 34 random are ID's (unimportant to the problem) and 2 specifies the two combinations following of '3 yes' and '2 no'. The 3 preceding 'yes' specifies the length of the string following, and the same is true for the 'no' with a 2 before it. Where we can have a variable number of these combinations following and we want to catch them all with the sscanf. Does anyone know of any way to do this with sscanf? Thanks a lot!

Original source