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!
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With