此符号是否被视为整数的开始?如果是这样,为什么这种输入被视为失败?如果不是,为什么会被消费呢?或者这是一种完全没有定义的行为?
以下是从fscanf()
起的适用范围:
An input item is read from the stream, ... . An input item is defined as the longest sequence of input characters which does not exceed any specified field width and which is, or is a prefix of, a matching input sequence.348 The first character, if any, after the input item remains unread. If the length of the input item is zero, the execution of the directive fails; this condition is a matching failure ... .
C23dr § 7.23.6.2 9
348 fscanf
pushes back at most one input character onto the input stream. Therefore, some sequences that are acceptable to
strtod
, strtol
, etc., are unacceptable to fscanf
.
在我阅读本文时,OP的输入为"-*"
,直到读取了'*'
,scanf()
才意识到输入匹配失败,并将'*'
推回到stdin
(按照规范的要求).Some系统将成功地将'-'
也推回(请注意,脚注本身是信息性的--而不是规范.),但OP的系统没有.
Moral of the story:
(f)scanf()
is difficult to use with faulty input. Instead for line input, use fgets()
to read the line into a string and then parse the string.
请注意,还会使用可选的前导空格字符(带有"%d"
).
注意,有更长的输入序列,如"-.*"
对应"%f"
,这会导致问题.