假设我们有
int n;
sscanf(" 42", "%2d", &n);
n
应该是 4(“%2d”所占的空格)还是 42(忽略空格,使 scanf 读取 3 个字符)?
ideone implementation读取 3 个字符
最佳答案
sscanf()
的 POSIX 规范
对处理过程相当清楚:
The format is a character string, … composed of zero or more directives. Each directive is composed of one of the following: one or more white-space characters (
<space>
,<tab>
,<newline>
,<vertical-tab>
, or<form-feed>
); an ordinary character (neither '%
' nor a white-space character); or a conversion specification. Each conversion specification is introduced by the character '%
' [CX] ⌦ or the character sequence "%n$", ⌫ after which the following appear in sequence:…
A directive that is a conversion specification defines a set of matching input sequences, as described below for each conversion character. A conversion specification shall be executed in the following steps.
Input white-space characters (as specified by
isspace
) shall be skipped, unless the conversion specification includes a[
,c
,C
, orn
conversion specifier.An item shall be read from the input, unless the conversion specification includes an
n
conversion specifier. An input item shall be defined as the longest sequence of input bytes (up to any specified maximum field width, which may be measured in characters or bytes dependent on the conversion specifier) which is an initial subsequence of a matching sequence. The first byte, if any, after the input item shall remain unread. If the length of the input item is 0, the execution of the conversion specification shall fail; this condition is a matching failure, unless end-of-file, an encoding error, or a read error prevented input from the stream, in which case it is an input failure.
如果转换规范 (%…
) 跳过了空白,则它不计入字段宽度;跳过发生在任何计数之前。
C11 中的等效规范 §7.21.6.2 The fscanf
function非常相似(当然,它不包括“C 扩展”标记)。
关于c - scanf 'maximum field width' 包含空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55581903/