2013-05-17 86 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 

分享和享受。