-
sscanf & whitespaces
I have a couple of strings that are formatted like this :
"string1" "string2" "string3"
eg :
"testing" "hi_there" "56"
I want to break up this string into 3 strings so I call this :
Code:
char *input = "\"testing\" \"hi_there\" \"56\"";
char score[16];
char name[64];
char value[16];
sscanf(input, "%s %s %s", score, name, value);
printf("%s %s %s\n", score, name, value);
The output is :
"testing" "hi_there" "56"
So far so good. I get a problem though when I have a string like this :
"testing" "I contain whitespaces" "56"
The output is wrong then. I also understand why. But I can't find a way to get the string between the 2 ' " 's WITH whitespaces.
Thanks in advance.
-
If you don't need to include the double-quotes within the destination string, I'd say go with something like this.
Code:
#include <stdio.h>
int main()
{
const char input[] = "\"testing\" \"I contain whitespaces\" \"56\"";
char score[16];
char name[64];
char value[16];
if ( sscanf(input, "\"%15[^\"]\" \"%63[^\"]\" \"%15[^\"]\"",
score, name, value) == 3 )
{
printf("\"%s\" \"%s\" \"%s\"\n", score, name, value);
}
return 0;
}
/* my output
"testing" "I contain whitespaces" "56"
*/
If you do need the double-quotes, I'd say write your own parsing function based on strchr or similar.