I’m trying to parse xxxxxx(xxxxx) format string using sscanf as following:
sscanf(command, "%s(%s)", part1, part2)
but it seems like sscanf does not support this format and as a result, part1 actually contains the whole string.
anyone has experience with this please share…
Thank you
Converting your code into a program:
When run, it produces ‘
Problem! n = 1‘.This is because the first
%sconversion specifier skips leading white space and then scans for ‘non white-space’ characters up to the next white space character (or, in this case, end of string).You would need to use (negated) character classes or scansets to get the result you want:
This produces:
Note the 31’s in the format; they prevent overflows.
With the given data, these two lines are equivalent and both safe enough:
The
%[...]notation is a conversion specification; so is%31[...].The C standard says:
The 31 is an example of the (optional) maximum field width. The
[...]part is a scanset, which could perhaps be regarded as a special case of thesconversion specifier. The%sconversion specifier is approximately equivalent to%[^ \t\n].The 31 is one less than the length of the string; the null at the end is not counted in that length. Since
part1andpart2are each an array of 32char, the%31[^(]or%31[^)]conversion specifiers prevent buffer overflows. If the first string of characters was more than 31 characters before the(, you’d get a return value of 1 because of a mismatch on the literal open parenthesis. Similarly, the second string would be limited to 31 characters, but you’d not easily be able to tell whether the)was in the correct place or not.