简体   繁体   中英

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.

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

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 %[^\\"]

The problem is that %s conversion specification reads input until it reach whitespace character. So, you have all the data after "username" in first variable.

1) in the whole string format you have to correct this "\\ with \\" . The \\ to mention that that the next character is a special character and " is a special character

2) you have to replace %s with %[^\\"] for both username and says . This above regular expression means that you want to catch string which does not contain " . so the catch of the string will stop at the first "

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM