2017-04-07 110 views
4

我正在閱讀一本書並解決一些問題。現在的問題是爲什麼「%d」與scanf中的格式字符串不等效爲「%d」

對於每個下面對scanf格式串,指明 兩個字符串是否是等價的。如果他們不是,顯示 他們如何可以區分。

的(a)"%d" veruss " %d"

(b)中"%d-%d-%d""%d -%d -%d"

(c)中"%f""%f "

(d)"%f,%f""%f, %f"

我的解決辦法是( a)自scanf d起相當於d iscards白色空間。對於(b)它們不是等同的,因爲scanf匹配-與空白空間。對於(c),它們不是等同的,因爲scanf將把緩衝區中的空白放回去。對於(d),它們是相同的,因爲scanf丟棄了空白區域。根據Chegg解決方案,以上所有問題都不相同。我錯了嗎?在這篇文章中,我想確保我的答案與Chegg解決方案相比是正確的。我已經閱讀過這本書,並且我有關於scanf的相當知識。

+1

[不同的scanf格式之間的不同]的可能的複製(http://stackoverflow.com/questions/38126126/difference-between-different-scanf-formats) – rsp

+1

@rsp , 不完全是。我已經提供了答案。另外,我將我的解決方案與Chegg解決方案進行比較。而且,這不是作業問題。 – CroCo

+0

@CroCo任何理由將列表格式恢復爲難以閱讀的文本塊? –

回答

0

你是對的,對選項(c)推理稍作修改。

「scanf會將緩衝區中的空白放回去。」

我真的不明白你的版本,但實際上,scanf()嚴格匹配與所提供的格式字符串輸入,並一起%f轉換說明,單個非前導空格必須與任何匹配空白的數量,直到讀取一個非空白字符。

引用C11,章§7.21.6.2

的空白字符(一個或多個)構成的指令是通過讀取輸入到 第一個非空白字符(這仍然是未讀)執行,或者直到沒有更多的字符可以被讀取 。該指令永遠不會失敗。

+0

在(c)中,'scanf'將等待用戶輸入一個非空白字符,正如我從書中理解的那樣,所以我對這些選項的索引是不相等的。 – CroCo

+0

'「%d-%d-%d」'和'「%d - %d - %d」'不一樣。一個輸入字符串「1-2-3」不會被前者解析,但會被後者解析 – nos

+0

@nos啊,我似乎錯過了,應該是對的。 –

1

"%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" 
相關問題