Reputation: 32912
Let's have this code
char input[] = "key: value";
char key[32], value[32];
sscanf(input, "%31[^:]:%*[ ]%31s", key, value);
There can be zero or more spaces after the :
, I'd like to store the key ond value into c-string variables. The code above can work with one or more spaces, but tough luck with zero spaces.
Is there a simple way how to parse such strings? No necessarily sscanf, but I'd like to avoid regex.
Edit
I found a reference supporting the accepted answer (what an useful, but non-intuitive feature):
the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).
Upvotes: 2
Views: 1879
Reputation: 754550
Just use "%31[^:]:%31s"
.
The %s
conversion specification skips leading blanks anyway, and stops at the first blank after one or more non-blanks.
If you decide you need blanks in the second field, but not the leading blanks, then use:
"%31[^:]: %31[^\001]"
(assuming it is unlikely that your string contains control-A characters that you're interested in). The blank in the format string skips zero or more blanks (strictly, zero or more white space characters).
Upvotes: 6