【问题标题】:sscanf error when getting multiple strings [duplicate]获取多个字符串时出现sscanf错误[重复]
【发布时间】:2022-06-10 21:00:22
【问题描述】:

我在 C 中标记一行,我的行是这样的:

2,1,alert temperature,hw,110C

我是这样读的

int         code;       //  1....32000
int         severity;   //  1....5
char        description[40];
char        origin[40] = "ZzZzZz";
char        thr[10] = "qQqQqQ"; non utilizzato
char        BUFF[250];

sscanf(BUFF, "%d,%d,%40[^,]s,%40[^,]s,%10s", &code, &severity, description, origin, thr);

警报温度之前正确读取originthr保持初始化值。

注意:字段长度可变(最多 40 个字符)

【问题讨论】:

  • 您使用 either [^,] s 格式说明符,但不能同时使用两者。您的代码将在前两个字符串之后寻找文字 s
  • "字段长度可变(最多 40 个字符)" --> off-by-1。 char description[40]; 最多可以将 39 个字符读入 字符串

标签: c scanf tokenize conversion-specifier


【解决方案1】:

格式字符串中转换说明符[]后面的字母s是多余的

sscanf(BUFF, "%d,%d,%40[^,]s,%40[^,]s,%10s", &code, &severity, description, origin, thr);

像这样重写调用

sscanf(BUFF, "%d,%d,%40[^,],%40[^,],%10s", &code, &severity, description, origin, thr);

否则sscanf 会尝试读取源字符串中的字母s

此外,用于输入字符串的长度修饰符应小于字符数组的长度,以便能够存储终止零字符“\0”。所以也要改变 scanf 的调用,比如

sscanf(BUFF, "%d,%d,%39[^,],%39[^,],%9s", &code, &severity, description, origin, thr);

【讨论】:

  • s 比冗余更糟糕 - 它正在造成伤害(寻找实际的 's' 字符,如链接副本的this answer 中所述)。可能有更好的副本,但我仍在寻找。
  • "...%10s" 不如"...%9s" 避免char thr[10] 溢出?
  • @chux-ReinstateMonica 好话。我没注意这个。
  • %40[^,],%40[^,]类似
猜你喜欢
  • 2021-12-04
  • 2013-08-31
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 2012-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多