本文介绍了如何忽略 fscanf() 中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 fscanf 来忽略所有空格并且不保留它.我尝试使用类似 (*)[^\n] 之间的组合作为: fscanf(file," %*[^\n]s",);当然死机了,有没有什么办法只用fscanf来解决?

I need to use fscanf to ignore all the white spaces and to not keep it.I tried to use something like the combination between (*) and [^\n] as: fscanf(file," %*[^\n]s",);Of course it crashed, is there any way to do it only with 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() 读取所有行,但没有保留它!

Solved !change the original fscanf() to : fscanf(file," %*[^\n]s"); read all the line exactly as fgets() but didnt keep it!

推荐答案

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

Using a space (" ") in the fscanf format causes it to read and discard whitespace on the input until it finds a non-whitespace character, leaving that non-whitespace character on the input as the next character to be read. So you can do things like:

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

来自:

使用 fscanf 或 fgets 忽略空白?

这篇关于如何忽略 fscanf() 中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 21:11