假设我有一个文件dog.txt
The quick brown fox jumps over the lazy dog.
我可以像这样从文件中读取
# include <stdio.h>
int main(){
char str[10];
FILE *fp;
fp = fopen("dog.txt", "r");
fscanf(fp, "%[ABCDEFGHIJKLMNOPQRSTUVWXYZ]", str);
printf("%s\n", str);
return 0;
}
程序将输出T
。但是,我可以使用 POSIX 字符类(例如 [:upper:]
),而不是列出所有字母吗?
最佳答案
不,没有可移植的方法来做到这一点。某些实现允许您使用像 %[A-Z]
这样的字符范围,但 C 标准并不能保证这一点。 C99 §7.19.6.2/12 关于 [
转换说明符(添加了强调)是这样说的:
The conversion specifier includes all subsequent characters in the
format
string, up to and including the matching right bracket (]
). The characters between the brackets (the scanlist) compose the scanset, unless the character after the left bracket is a circumflex (^
), in which case the scanset contains all characters that do not appear in the scanlist between the circumflex and the right bracket. If the conversion specifier begins with[]
or[^]
, the right bracket character is in the scanlist and the next following right bracket character is the matching right bracket that ends the specification; otherwise the first following right bracket character is the one that ends the specification. If a-
character is in the scanlist and is not the first, nor the second where the first character is a^
, nor the last character, the behavior is implementation-defined.
POSIX.1-2008 description具有几乎相同的措辞(甚至在意外冲突的情况下遵循 ISO C 标准),因此在使用 POSIX 系统时,在这种情况下没有额外的保证。
关于c - 带有字符类的 fscanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13114073/