How to capture length of sscanf'd string?

c, c++, parsing, scanf, string

Solution

You can use the `%n` conversion specifier, which doesn't consume any input - instead, it expects an `int *` parameter, and writes the number of characters consumed from the input into it:

int consumed;

sscanf(serialized + start, "%d%n", &len, &consumed);
start += consumed;

(But don't forget to check that `sscanf()` returned > 0!)

Problem

I'm parsing a string that follows a predictable pattern: - 1 character - an integer (one or more digits) - 1 colon - a string, whose length came from #2 For example: ``` s5:stuff ``` I can see easily how to parse this with PCRE or the like, but I'd rather stick to plain string ops for the sake of speed. I know I'll need to do it in 2 steps because I can't allocate the destination string until I know its length. My problem is gracefully getting the offset for the start of said string. Some code: ``` unsigned start = 0; char type = serialized[start++]; // get the type tag int len = 0; char* dest = NULL; char format[20]; //... switch (type) { //... case 's': // Figure out the length of the target string... sscanf(serialized + start, "%d", &len); // <code type='graceful'> // increment start by the STRING LENGTH of whatever %d was // </code> // Don't forget to skip over the colon... ++start; // Build a format string which accounts for length... sprintf(format, "%%%ds", len); // Finally, grab the target string... sscanf(serialized + start, format, string); break; //... } ``` That code is roughly taken from what I have (which isn't complete because of the issue at hand) but it should get the point across. Maybe I'm taking the wrong approach entirely. What's the most graceful way to do this? The solution can either C or C++ (and I'd actually like to see the competing methods if there are enough responses).

Original source