使用 sscanf 获取零个或多个长度的字符串

问题描述 投票:0回答:1

以下代码:

#include <stdio.h>

int main(void) {
  char buf[80] = "salam";
  const char *fmt = "\"%79[^\"]\"";
  int n;

  n = sscanf("\"\"", fmt, buf);
  printf("%d fields were read. buf = '%s'\n", n, buf);
  n = sscanf("\"hamidi\"", fmt, buf);
  printf("%d fields were read. buf = '%s'\n", n, buf);
}

输出:

读取了 0 个字段。 buf = '萨拉姆'
已读取 1 个字段。 buf = '哈米迪'

这表明sscanf函数无法读取指定格式字符串的空字符串。是否有一个很好的替代正则表达式格式字符串来通过 sscanf 函数读取长度为零到最多 79 个字符的字符串?换句话说,我希望第一个 sscanf 将 ' ' 插入 buf[0] 并返回 1 而不是 0。有办法吗?

c scanf
1个回答
0
投票

确实

sscanf
和朋友无法处理空字段。标准库中没有直接的替代方案,但您可以使用循环或使用
strcspn
strchr
编写一个简单的解析器。

© www.soinside.com 2019 - 2024. All rights reserved.