在C中,什么是“%n”?这段代码是如何工作的?

时间:2013-05-17 13:07:39

标签: c format scanf

在c编程语言中,什么是占位符“%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
    }

- 此代码获取一行作为字符数组,然后扫描此字符数组中的数字, 例如:如果*s="12 34 567" 第一次x = 12 下一次x = 34 最后x = 567

3 个答案:

答案 0 :(得分: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.

答案 1 :(得分:0)

此处,"%n"表示到目前为止读取的字符数。

答案 2 :(得分: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 

分享并享受。