"%d" 和 " %d" 根据 OP 的推理是相同的。
它们与 "123" 和 " 456" 等预期的数字输入肯定相同。剩下的一个考虑是FILE 与"abc" 与" xyz" 相比,失败的指针在哪里? "%d" 本身,first 消耗前导空白。所以没有区别。
...转换规范按以下步骤执行:C11dr §7.21.6.2 7
输入空白字符 ... 被跳过,除非规范包含 [、c 或 n 说明符。 §7.21.6.2 8
然后将文本转换为数字输入(对于"%d")。
下面的代码演示了等价性。
void next_testi(const char *s, const char *fmt, const char *pad) {
rewind(stdin);
int i = 0;
int count = scanf(fmt, &i);
int next = fgetc(stdin);
printf("format:\"%s\",%s count:%2d, i:%2d, next:%2d, text:\"%s\"\n", //
fmt, pad, count, i, next, s);
}
void next_test(const char *s) {
FILE *fout = fopen("test.txt", "w");
fputs(s, fout);
fclose(fout);
freopen("test.txt", "r", stdin);
next_testi(s, "%d", " ");
next_testi(s, " %d", "");
puts("");
}
int main() {
next_test("3");
next_test(" 4");
next_test("");
next_test(" ");
next_test("+");
next_test(" -");
next_test("X");
next_test(" Y");
}
输出
format:"%d", count: 1, i: 3, next:-1, text:"3" // scanf() return value 1:success
format:" %d", count: 1, i: 3, next:-1, text:"3"
format:"%d", count: 1, i: 4, next:-1, text:" 4"
format:" %d", count: 1, i: 4, next:-1, text:" 4"
format:"%d", count:-1, i: 0, next:-1, text:"" // scanf() return value EOF, next is EOF
format:" %d", count:-1, i: 0, next:-1, text:""
format:"%d", count:-1, i: 0, next:-1, text:" "
format:" %d", count:-1, i: 0, next:-1, text:" "
format:"%d", count: 0, i: 0, next:43, text:"+" // scanf() return value 0
format:" %d", count: 0, i: 0, next:43, text:"+"
format:"%d", count: 0, i: 0, next:45, text:" -"
format:" %d", count: 0, i: 0, next:45, text:" -"
format:"%d", count: 0, i: 0, next:88, text:"X"
format:" %d", count: 0, i: 0, next:88, text:"X"
format:"%d", count: 0, i: 0, next:89, text:" Y"
format:" %d", count: 0, i: 0, next:89, text:" Y"