【问题标题】:how to sscanf this string如何扫描这个字符串
【发布时间】:2014-02-27 11:07:26
【问题描述】:

如何扫描以下字符串

空(1)

空(20)

我尝试了以下但总是失败

int count;
sscanf(buf, "%*s(%d)", &count)

提前致谢!

【问题讨论】:

  • 空(1)和空(20)?这些是什么
  • 是他要扫描的字符串。

标签: c scanf


【解决方案1】:

改成

sscanf(buf, "%*[^(](%d", &count);

【讨论】:

    【解决方案2】:

    sscanf 总是以你给定的格式读取。

    您的测试字符串为空(1)但在 sscanf 中您使用了sscanf(buf, "%*s(%d)", &count)

    通过这种方式,你试图将“空”复制到计数,因为你不能将字符串分配给 int,所以它总是会失败。

    做一些类似的事情,

    int count;
    char s[20];
    sscanf(buf, "%*s(%d)",s, &count)
    

    【讨论】:

    • 你必须先为s分配内存
    • @BobAlmond - 我将始终引用此站点tutorialspoint.com/c_standard_library/c_function_sscanf.htm,并且没有这样的定义。我想你理解错了..
    • 这显然是错误的,即使你的“参考”说:This is an optional starting asterisk indicates that the data is to be read from the stream but ignored, i.e. it is not stored in the corresponding argument.。另外,请使用正确的参考,如en.cppreference.com 或参考标准,因为这些关注于拥有当前的标准定义,而不是教程。您的网站甚至没有真正提及迄今为止发布的各种 C 标准。
    • 这将工作。 * 禁止分配。 C11规范“格式应为......在%之后,以下依次出现......可选赋值-抑制字符*。”
    【解决方案3】:

    如果文本总是“empty(some int)”那么

    int count;
    int n=0;
    if (sscanf(buf, "empty(%d)%n", &count, &n) == 1) && (n > 0)) Success();
    

    sscanf() 将匹配char 以匹配char(尽管空格处理方式不同),直到达到"%d",然后它将尝试匹配int。扫描继续,将charchar 匹配,直到"%n" 将扫描的char 计数保存到n

    针对 1 测试返回值(扫描了 1 个参数,%n 个参数没有贡献)并看到 n 不再为 0,因此已知扫描已完全完成。 p>

    如果代码需要确保没有任何额外之后可以使用。

    if (sscanf(buf, "empty(%d)%n", &count, &n) == 1) && (buf[n] == '\0')) Success();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      相关资源
      最近更新 更多