7

I am trying to parse the following string with sscanf:

query=testword&diskimg=simple.img

How can I use sscanf to parse out "testword" and "simple.img"? The delimiter arguments for sscanf really confuse me :/

Thank you!

Jason Block
  • 155
  • 1
  • 3
  • 9

1 Answers1

16

If you know that the length of "testword" will always be 8 characters, you can do it like this:

char str[] = "query=testword&diskimg=simple.img";
char buf1[100];
char buf2[100];

sscanf(str, "query=%8s&diskimg=%s", buf1, buf2);

buf1 will now contain "testword" and buf2 will contain "simple.img".

Alternatively, if you know that testword will always be preceded by = and followed by &, and that simple.img will always be preceded by =, you can use this:

sscanf(str, "%*[^=]%*c%[^&]%*[^=]%*c%s", buf1, buf2);

It's pretty cryptic, so here's the summary: each % designates the start of a chunk of text. If there's a * following the %, that means that we ignore that chunk and don't store it in one of our buffers. The ^ within the brackets means that this chunk contains any number of characters that are not the characters within the brackets (excepting ^ itself). %s reads a string of arbitrary length, and %c reads a single character.

So to sum up:

  • We keep reading and ignoring characters if they are not =.
  • We read and ignore another character (the equal sign).
  • Now we're at testword, so we keep reading and storing characters into buf1 until we encounter the & character.
  • More characters to read and ignore; we keep going until we hit = again.
  • We read and ignore a single character (again, the equal sign).
  • Finally, we store what's left ("simple.img") into buf2.
dst2
  • 495
  • 5
  • 16