【问题标题】:Control whole string with sscanf用 sscanf 控制整个字符串
【发布时间】:2012-12-04 11:15:55
【问题描述】:

我需要在c中解析一个格式为“foo=%d”的字符串,我需要检查格式是否正确并读取int值。

我的初始代码是:

int foo_set = 0;
int foo;
if (sscanf(text, "foo=%d", &foo) == 1)
    foo_set = 1;

但是代码应该拒绝诸如“foo=5$%£”之类的输入。 这段代码能用吗?

int foo_set = 0;
int foo;
char control;
if (sscanf(text, "foo=%d%c", &foo, &control) == 1)
    foo_set = 1;

使用control 字符代码检查没有额外的输入。 有没有更好/更正确的方法来做到这一点?

谢谢

【问题讨论】:

  • Would this code work?。为什么不跑过去看看?

标签: c parsing scanf


【解决方案1】:

使用%n 格式说明符来确定处理结束的位置并检查它是否匹配字符串的长度:

const char* text = "foo=4d";
int pos;
int foo;

if (sscanf(text, "foo=%d%n", &foo, &pos) == 1 &&
    pos == strlen(text))
{
    /* Valid as all of text consumed. */
}

来自 C99 标准的格式说明符 n 的说明:

不消耗任何输入。 对应的参数应该是一个指向 要写入的有符号整数 从中读取的字符数 到目前为止,通过调用 fscanf 函数得到的输入流。执行一个 %n 指令不会增加在 fscanf 函数的执行完成。没有参数被转换, 但一个被消耗了。如果转换规范包括分配抑制 字符或字段宽度,行为未定义。

https://ideone.com/d1rhPf 上查看演示。

【讨论】:

  • 我不知道这是多么真实或最新,但根据 Linux scanf 手册页:The C standard says: "Execution of a %n directive does not increment the assignment count returned at the completion of execution" but the Corrigendum seems to contradict this. Probably it is wise not to make any assumptions on the effect of %n conversions on the return value.
猜你喜欢
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
相关资源
最近更新 更多