简体   繁体   中英

Get how many characters sscanf has read? (%n)

I have a string structured such as "[first something]=[second something"]

I think sscanf would be a way to seperate them!

However, scan never reports the offset properly with %n.

The line of code is something very much like:

char data[100];
char source[] = "username=katy"
int offset=-1;
sscanf([source],"%[^=],%s%n",data,&offset)
printf("sscanf is reporting %s with an offset of %i\n"

)

but the output always looks like:

sscanf is reporting username with an offset of -1

Could someone be so kind as to clear this up for me?

(Yes, I know this leaves us prone to a buffer overflow error - that is garuneteed against a little earlier in the code...)

Your comma in the scanf format string makes no sense. Instead of "%[^=],%s%n" , try "%[^=]=%s%n" . You should also put field width limits on both of the strings or else you could overflow the destination buffers, and you've passed too few arguments to sscanf (only one of the strings, not the other one).

A corrected version of the code might look like:

char key[100], data[100];
char source[] = "username=katy"
int offset=-1;
sscanf(source,"%99[^=]=%99s%n",key,data,&offset)
printf("sscanf is reporting %s with an offset of %i\n", data, offset);

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