【问题标题】:How to scan for numbers in strings separated by commas in c如何在c中扫描以逗号分隔的字符串中的数字
【发布时间】:2018-04-21 16:57:02
【问题描述】:

我正在尝试扫描以逗号分隔的字符串中的 RGB 值

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

但是当我尝试打印出这些值时,它们都是 0。我该怎么做?我只是想把这部分写下来,但这将被实现为根据音乐节拍点亮 LED 灯条的代码,所以这将需要循环,所以如果有人也可以帮助这部分,那就太好了。

【问题讨论】:

  • strtok( colors, "," )循环

标签: c string scanf


【解决方案1】:

您拨打int sscanf(const char *str, const char *format, ...) 是错误的。第一个参数应该是您要从中解析数据的字符串,而不是格式。此外,您必须将格式从"%3[^,]%d" 更改为"%d,%d,%d"。所以你的代码应该是:

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

代替:

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

还可以考虑增加colors 的大小,以便它可以容纳字符串的所有字符以及空字符\0

编辑:正如@chux 在 cmets 中提到的,应检查sscanf 的返回值以处理错误情况:

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

【讨论】:

  • 健壮的代码检查sscanf() 的返回值以确保扫描成功。建议if (sscanf(colors, "%d,%d,%d", &r, &g, &b) != 3) do_some_error_handling();
  • @chux 我完全同意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 2021-11-01
  • 2011-06-20
  • 1970-01-01
  • 1970-01-01
  • 2013-03-16
  • 1970-01-01
相关资源
最近更新 更多