Jerome
Jerome

Reputation: 1215

C sscanf and string format

I have a little bit of a problem while understanding the sscanf string formatting.

I have that string stored in str: 192.168.0.100/act?bla=

I want with this code to have bla stored inside my "key" variable and the remaining stuff (after the '=') in my "buf" variable

char str[] = "192.168.0.100/act?bla=";
char key[20];
char buf[100];
sscanf(str, "%*[^?] %[^=] %s", key, buf);

Upvotes: 1

Views: 2324

Answers (2)

hmjd
hmjd

Reputation: 121961

The ? and = will not be consumed so include them in the format specifier:

sscanf(str, "%*[^?]?%[^=]=%s", key, buf);

See demo at http://ideone.com/YoRMh3 .

To prevent buffer overrun specify the maximum number of characters that can be read by each specifier, one less than the target array to allow for null termination, and ensure that both arrays were populated by checking the return value of sscanf():

if (2 == sscanf(str, "%*[^?]?%19[^=]=%99s", key, buf))
{
    printf("<%s>\n", key);
    printf("<%s>\n", buf);
}

In order to ensure that the buf value is not truncated, you can use the %n format specifier that populates an int indicating the position at which processing stopped (note the %n has no effect on the return value of sscanf()). If the entire input was processed the end position is strlen(str):

int pos;
if (2 == sscanf(str, "%*[^?]?%19[^=]=%5s%n", key, buf, &pos) &&
    strlen(str) == pos)
{
    printf("<%s>\n", key);
    printf("<%s>\n", buf);
}

Upvotes: 8

You can add the exptected characters so they will be read and ignored:

sscanf(str, "%*[^?]?%[^=]=%s", key, buf);

Note that '?' and '=' are still in the stream and aren't read after [^=] is processed.

Upvotes: 1

Related Questions