AllTheTime AllTheTime - 2 months ago 8
C Question

C - can I use sscanf when half of the format is indeterminate?

I just recently started learning C, so don't assume I know anything...

Say I have a string like this

"XXX YYY ZZZ A something heyyy O"


That I want to parse into 4 variables like so:

[XXX] [YYY] [ZZZ] [An uncertain string]


The first three values are guaranteed to exist separated by spaces, but everything after from
An
will have an indeterminate number of spaces.

I can already do:

sscanf(string, "%s %s %s", one, two, three);


To capture the first 3 values, but is there a way to capture the last bit with sscanf, or do I need to do something tricky with
strtok
?

Answer

Yes, you mean that you want to capture 3 strings separated with spaces and then the rest of it

if (sscanf(string, "%s%s%s%[^\n]", one, two, three, four) != 4) {
    fprintf(stderr, "The string `%s' doesn't match the format\n");
}

And better be careful with a buffer overflow

char one[100];
char two[100];
char three[100];
char four[100];

if (sscanf(string, "%99s%99s%99s%99[^\n]", one, two, three, four) != 4) {
    fprintf(stderr, "The string `%s' doesn't match the format\n");
}
Comments