简体   繁体   中英

How to scan for numbers in strings separated by commas in c

I am trying to scan for RGB values in a string separated by commas

char colors[11]= "255,80,120";
int r,g,b;
sscanf("%3[^,]%d", colors, &r, &g, &b);

But when I try and print out those values they are all 0's. How am I supposed to do this? I am just trying to get this part down but this will be implemented into code that lights up an LED strip to the beat of music so this will need to loop so if anyone can help with that part too that'd be great.

Your call to int sscanf(const char *str, const char *format, ...) , is wrong. The first parameter, should be the string from which you are going to parse data not the format. Also, you have to change the format from "%3[^,]%d" to "%d,%d,%d" . So your code should be:

sscanf(colors, "%d,%d,%d", &r, &g, &b);

instead of:

sscanf("%3[^,]%d", colors, &r, &g, &b);

Also consider increasing the size of colors so that it can hold all characters of the string as well as well as the null character \\0 .

Edit : As mentioned by @chux in the comments, the return value of sscanf should be checked in order to handle error cases:

if (sscanf(colors, "%d,%d,%d", &r, &g, &b) != 3) {
    /* Handle errors. */
}

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