2013-05-17 30 views
0

在c編程語言中,佔位符「%n」是什麼? 以及下面的代碼如何工作?,什麼是「%n」?這個代碼是如何工作的?

char s[150]; 
    gets(s); 
    int read, cur = 0,x; 
    while(sscanf(s+cur, "%d%n", &x, &read) == 1) 
    { 
     cur+= read; 
     /// do sth with x 
    } 

- 這段代碼獲得一個行字符數組,然後從這個字符數組掃描的數字, 例如:如果x = 12 下一次*s="12 34 567" 首次x = 34 最後x = 567

+1

檢查此問題http://stackoverflow.com/questions/3401156/what-is-the-use-of-n-format-specifier-in-c#answer-3401176 – arthankamal

+0

有人應該發佈標準或規範或手冊或者解釋這樣的事情的書。在地球上任何地方都找不到任何人。 –

+0

@EricPostpischil我希望你是諷刺。 – Sebivor

回答

5

從手冊頁

n  Nothing is expected; instead, the number of characters consumed 
       thus far from the input is stored through the next pointer, 
       which must be a pointer to int. This is not a conversion, 
       although it can be suppressed with the * assignment-suppression 
       character. The C standard says: "Execution of a %n directive 
       does not increment the assignment count returned at the comple‐ 
       tion of execution" but the Corrigendum seems to contradict this. 
       Probably it is wise not to make any assumptions on the effect of 
       %n conversions on the return value. 
+0

correctundums矛盾是錯誤的。最新的標準是最好的,其中糾正和包括了勘誤中的錯誤例子。 – Sebivor

0

這裏,"%n" repr表示迄今閱讀的字符數。

0

%n將已經處理的輸入字符串的字符數存儲到相關參數中;在這種情況下,read會得到這個值。我改寫了你的代碼有點轉儲作爲代碼執行所發生的每個變量:

#include <stdio.h> 

int main(int argc, char **argv) 
    { 
    char *s = "12 34 567"; 
    int read=-1, cur = 0, x = -1, call=1; 

    printf("Before first call, s='%s' cur=%d x=%d read=%d\n", s, cur, x, read); 

    while(sscanf(s+cur, "%d%n", &x, &read) == 1) 
    { 
    cur += read; 

    printf("After call %d, s='%s' cur=%d x=%d read=%d\n", call, s, cur, x, read); 

    call += 1; 
    } 
    } 

產生以下

Before first call, s='12 34 567' cur=0 x=-1 read=-1 
After call 1,  s='12 34 567' cur=2 x=12 read=2 
After call 2,  s='12 34 567' cur=5 x=34 read=3 
After call 3,  s='12 34 567' cur=9 x=567 read=4 

分享和享受。