是否可以为scanf指定一个由多个`^`字符组成的字符串?
Is it possible to specify a string consisting of a number of `^` characters for scanf?
在 C-scanf
格式中,如何指定我想要一个字符 ^
?
"%[^]"
不适用于 GNU scanf
,因为开头的 ^
具有否定意义。
scanf is it possible to specify a string consisting of a number of ^
characters?
做一个简单的%[^]
是不可能的。
%[^]
实际上是无效的-初始[
没有关闭。 %[^]]
被解释为除 ]
.
之外的所有字符
假设 %[^]
有效,那么它会出现歧义:%[^]]
可以解释为仅由 ^
后跟 ]
组成的字符串。或者想象一下 $[^]abc]
。我相信扫描仅由 ^
组成的字符串的能力被牺牲以赋予 ^
它的功能,这是一个合理的牺牲。
解决实践中的问题,不用scanf
,自己写。或者您可以执行类似 "%[^]
的操作 - 还可以扫描输入中不存在的其他内容,例如 0x01
字节。
来自 C99 7.19.6.2 (and this pdf)(强调我的):
[
[...]
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 scan list) 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. [...]
因此,如果转换为 %[]
或 %[^]
,则 ]
在扫描列表中,下一个 ]
将结束扫描列表。
作为解决方法,您可以在扫描列表中指定 ^
否定除 ^
之外的所有字符,仅有效扫描 ^
- %[^^]
.
在 C-scanf
格式中,如何指定我想要一个字符 ^
?
"%[^]"
不适用于 GNU scanf
,因为开头的 ^
具有否定意义。
scanf is it possible to specify a string consisting of a number of
^
characters?
做一个简单的%[^]
是不可能的。
%[^]
实际上是无效的-初始[
没有关闭。 %[^]]
被解释为除 ]
.
假设 %[^]
有效,那么它会出现歧义:%[^]]
可以解释为仅由 ^
后跟 ]
组成的字符串。或者想象一下 $[^]abc]
。我相信扫描仅由 ^
组成的字符串的能力被牺牲以赋予 ^
它的功能,这是一个合理的牺牲。
解决实践中的问题,不用scanf
,自己写。或者您可以执行类似 "%[^]
的操作 - 还可以扫描输入中不存在的其他内容,例如 0x01
字节。
来自 C99 7.19.6.2 (and this pdf)(强调我的):
[
[...]
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 scan list) 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. [...]
因此,如果转换为 %[]
或 %[^]
,则 ]
在扫描列表中,下一个 ]
将结束扫描列表。
作为解决方法,您可以在扫描列表中指定 ^
否定除 ^
之外的所有字符,仅有效扫描 ^
- %[^^]
.