简体   繁体   中英

How can I use sscanf to read a string between brackets?

I have some code reading a text file and scanning for words between brackets: '[' and ']'.

When I find the line starting with a '[' I read the string with:

line[64] = "[word]";
sscanf(line, "[%s]", resource);

printf("%s\n",resource);

==> word]

but I always end up with the string+the bracket. How can i format sscanf to only read the string without the bracket at the end?

Exclude the ] from the set of characters the scanf() reads:

char resource[100];
if (sscanf(line, "[%99[^]]]", resource) != 1) /* error */;

/* same as */
if (sscanf(line, "[" "%99[^]]" "]", resource) != 1) /* error */;
/*          literal   scanset   literal */

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