【问题标题】:How to force scanf to match whitespace?如何强制 scanf 匹配空格?
【发布时间】:2015-05-03 10:51:14
【问题描述】:

我正在尝试使用 fscanf() 来读取 前后必须有空格的字符:

fscanf( input, "%*[ \t]%c%*[ \t]", output )

但不幸的是,"%*[ \t]" 格式说明符接受零个或多个匹配项。无论如何我可以要求它接受至少一个匹配,还是我需要使用getc()之类的东西?

【问题讨论】:

  • fscanf 和空格相处得不是很好,所以 IMO 你最好用fgetc 一次得到一个字符,或者fgets 得到一个行时间,然后自己解析。
  • fscanf() 不适用于正则表达式匹配。
  • 类似char sp1[2], sp2[2], output; if (3 == fscanf( input, "%1[ \t]%c%1[ \t]", sp1, &output, sp2 )) Good(); 但同意@user3386109
  • 顺便说一句:"%*[ \t]" 不接受零匹配。
  • 如果匹配零个字符(中止读取),则 [ 说明符将失败。如果您发布了一些与您预期不匹配的示例输入,这可能会有所帮助

标签: c scanf format-specifiers character-class


【解决方案1】:

可以使用fscanf() 解决这个帖子,但让我们看看fgetc() 方法。

// return 1 on success, else return 0
int GetSpaceCharSpace(FILE *istream, int *ch) {
  *ch = fgetc(istream);
  if (!isspace(*ch))
    return 0;

  // consume additional leading spaces as OP said "accept at least one match"
  while (isspace(*ch = fgetc(istream)))
    ;
  // Code has a non-white-space

  // Success if next char is a white-space
  return isspace(fgetc(istream));
}

【讨论】:

    猜你喜欢
    • 2021-12-02
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多