【问题标题】:how to ignore whitespaces in fscanf()如何忽略 fscanf() 中的空格
【发布时间】:2013-12-20 21:56:23
【问题描述】:

我需要使用fscanf 来忽略所有空格并且不保留它。 我尝试使用类似(*) 和[^\n] 之间的组合的东西:fscanf(file," %*[^\n]s",); 当然崩溃了,有什么办法只用fscanf吗?

代码:

int funct(char* name)
{
   FILE* file = OpenFileToRead(name);
   int count=0; 
   while(!feof(file)) 
   {
       fscanf(file," %[^\n]s");
       count++;
   }
   fclose(file);
   return count;
}

解决了! 将原来的 fscanf() 更改为: fscanf(file," %*[^\n]s"); 完全按照fgets() 阅读所有行,但没有保留它!

【问题讨论】:

  • 我们能看到崩溃的代码吗?我们无法修复我们看不到的东西。
  • int funct(char* name) { FILE* file = OpenFileToRead(name);整数计数=0; while(!feof(file)) { fscanf(file," %[^\n]s");计数++; } fclose(文件);返回计数; }

标签: c scanf


【解决方案1】:

在 fscanf 格式中使用空格 (" ") 会导致它读取并丢弃输入上的空白,直到找到非空白字符,将输入上的非空白字符作为下一个要读取的字符。因此,您可以执行以下操作:

fscanf(file, " "); // skip whitespace
getc(file);        // get the non-whitespace character
fscanf(file, " "); // skip whitespace
getc(file);        // get the non-whitespace character

或

fscanf(file, " %c %c", &char1, &char2); // read 2 non-whitespace characters, skipping any whitespace before each

来自:

Ignoring whitepace with fscanf or fgets?

【讨论】:

    【解决方案2】:

    您的代码崩溃了,因为您在 fscanf 调用中的格式说明符中有一个 %s,并且您没有将 fscanf 传递给您希望它写入它找到的字符串的 char *。

    见http://www.cs.utah.edu/~zachary/isp/tutorials/io/io.html。

    【讨论】:

      【解决方案3】:

      来自 fscanf 手册页:

         A directive is one of the following:
        ·      A sequence of white-space characters (space, tab, newline, etc.;
                see isspace(3)).  This directive matches  any  amount  of  white
                space, including none, in the input.
      

      所以

      fscanf(file, " %s\n");
      

      在读入字符之前会跳过所有空格。

      【讨论】:

      • fscanf(file, " %s\n") 有问题:1) 没有匹配%s 的目的地。 2) "%s" 前面的 " " 不需要,因为 "%s" 无论如何都会消耗前导空格。 3) "\n" 对空白进行同样不需要的扫描。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-25
      • 2021-12-31
      • 1970-01-01
      • 2015-03-31
      相关资源
      最近更新 更多