c - 带有字符类的 fscanf

标签 c

假设我有一个文件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/

相关文章:

c++ - 如何以编程方式使系统崩溃

c# - Visual Studio安装C#组件后无法打开vcxproj

c - _Generic 发出奇怪的 gcc 警告

c++ - 这行代码是什么意思*((int*)(0))=1;?

c - 测量二级缓存吞吐量的解密作业

c - 使用 -l 标志链接静态库

c - 链接器无法在c中归档实现文件

objective-c - 从 C 函数调用 Objective-C 对象方法

c - 为什么 gcc 不为 int 和 char 产生类型不匹配警告?

c - OpenCV:如何强制图像窗口出现在其他窗口之上?