Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract from string in c using sscanf

I am trying to use sscanf to extract specific values of name and msg from a string {"username":"ece","says":"hello"} as following:

sscanf(data, "{"\username"\:"\%s"\,"\says"\:"\%s"\}", name, msg);

I need 'ece' in name and 'hello' in msg but I am getting ece","says":"hello" in name and msg remains empty.

like image 876
WiData Avatar asked Dec 05 '12 16:12

WiData


2 Answers

The %s format stops at the next white space. You need it to stop earlier, at the '"', so you need to use a character set,

sscanf(data, "{\"username\":\"%[^\"]\",\"says\":\"%s\"}", name, msg);
                              ^^^^^^
                          read up to the next double quote
like image 161
Daniel Fischer Avatar answered Nov 16 '22 22:11

Daniel Fischer


You need to put the escape \ before the escaped character.

sscanf(data, "{\"username\":\"%s\",\"says\":\"%s\"}", name, msg);

And unless there is a white space after the username, all that's in the buffer will be read into name.

Use an inverse character set instead of %s, like this %[^\"]

like image 2
StoryTeller - Unslander Monica Avatar answered Nov 16 '22 20:11

StoryTeller - Unslander Monica