"%d"
和" %d"
根據OP的推理是相同的。
它們肯定與預期的數字輸入相同,如"123"
和" 456"
。剩餘的考慮因素是FILE
指針失敗,與" xyz"
? "%d"
本身,第一消耗領先的空白。所以沒有區別。
...A轉換規範在下面的步驟執行:C11dr§7.21.6.27
輸入空白字符...被跳過,除非本說明書包括一個[
,c
,或n
說明符。 §7.21.6.28
然後文字,數字輸入轉換(對於"%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"
[不同的scanf格式之間的不同]的可能的複製(http://stackoverflow.com/questions/38126126/difference-between-different-scanf-formats) – rsp
@rsp , 不完全是。我已經提供了答案。另外,我將我的解決方案與Chegg解決方案進行比較。而且,這不是作業問題。 – CroCo
@CroCo任何理由將列表格式恢復爲難以閱讀的文本塊? –