Sscanf delimiters for parsing?

I am trying to parse the following line using sscanf:

query=testword&diskimg=simple.img 

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

Thanks!

+4
source share
1 answer

If you know that the word 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 precede = and is followed by &, and that simple.img will always precede =, you can use this:

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

This is rather cryptic, so here's the summary: each% marks the beginning of a piece of text. If there is * followed by%, this means that we ignore this chunk and do not store it in one of our buffers. The ^ element inside brackets means that this piece contains any number of characters that are not characters in brackets (except for ^ itself). % s reads a string of arbitrary length, and% c reads one character.

So to summarize:

  • We continue to read and ignore characters if they are not =.
  • We read and ignore another symbol (equal sign).
  • Now we are on the test word, so we continue to read and store the characters in buf1 until we meet the and character.
  • More characters to read and ignore; we keep going until we press = again.
  • We read and ignore one character (again an equal sign).
  • Finally, we save what remains ("simple.img") in buf2.
+11
source

All Articles