如何忽略 fscanf() 中的空格

ols*_*ynt 6 c scanf

我需要用来fscanf忽略所有的空格而不是保留它。我尝试使用类似(*)[^\n]as之间的组合: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;
}
Run Code Online (Sandbox Code Playgroud)

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

gau*_*430 6

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

fscanf(file, " "); // skip whitespace
getc(file);        // get the non-whitespace character
fscanf(file, " "); // skip whitespace
getc(file);        // get the non-whitespace character
Run Code Online (Sandbox Code Playgroud)

或者

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

从:

使用 fscanf 或 fgets 忽略空白?