如何强制scanf匹配空格?

时间:2015-03-02 22:36:12

标签: c scanf format-specifiers character-class

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

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

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

1 个答案:

答案 0 :(得分: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));
}