0

在 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

4

3 回答 3

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.
于 2013-05-17T13:10:56.690 回答
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 

分享和享受。

于 2013-05-17T13:22:26.540 回答
0

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

于 2013-05-17T13:11:49.263 回答