简体   繁体   English

如何在C中用逗号分隔的字符串中扫描数字

[英]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 我正在尝试扫描以逗号分隔的字符串中的RGB值

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. 但是,当我尝试打印这些值时,它们全都是0。 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. 我只是想把这部分放下来,但是这将被实现为代码,以点亮音乐节拍的LED灯带,因此这将需要循环播放,所以如果有人也可以帮助那部分,那就太好了。

Your call to int sscanf(const char *str, const char *format, ...) , is wrong. 您对int sscanf(const char *str, const char *format, ...)调用是错误的。 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" . 另外,您必须将格式从"%3[^,]%d"更改为"%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 . 还可以考虑增加colors的大小,以便它可以容纳字符串的所有字符以及空字符\\0

Edit : As mentioned by @chux in the comments, the return value of sscanf should be checked in order to handle error cases: 编辑 :正如@chux在评论中提到的,应该检查sscanf的返回值以处理错误情况:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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