如何忽略fscanf()中的空格
我需要使用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()
读取所有行,但没有保留它!
使用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
从:
用fscanf或fgets忽略空格?
您的代码崩溃是因为fscanf
调用中的格式说明符中有%s
,并且您没有将fscanf
传递给您希望它写入找到的字符串的char *
。
见http://www.cs.utah.edu/~zachary/isp/tutorials/io/io.html 。
来自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");
在读取字符之前将跳过所有空格。