What does the scanf specifier "n" scan?

As part of the program, I process the commands as a series of tokens. So far I have:

void exec_this(char* cmd) {
  char token[100] = {0};
  sscanf(cmd, "%s", token)
  if(0 == strcmp(token, "add")) {
    char arg1[100] = {0};
    sscanf(cmd, "%*s%s", arg1);    
    // continue parsing more args...
  }
}

"% * s" is ugly, especially when there are many arguments.

Looking at http://www.cplusplus.com/reference/cstdio/scanf/ , there is a possible qualifier "n" for retrieving "characters read so far." Not sure what “reading” means in this case, because there are spaces and so on in lines that are not part of the extracted line; "add foo 42". This is how I want it to work, but not sure if this is correct:

void exec_this(char* cmd) {
  char token[100] = {0};
  int n;
  sscanf(cmd, "%s%n", token, &n);
  if(0 == strcmp(token, "add")) {
    char arg1[100] = {0};
    sscanf(&cmd[n], "%s%n", arg1, &n);
    // continue parsing more args...
  }
}
+4
source share
2 answers

The number of characters read so far includes all spaces:

int a, b, c;
sscanf("     quick  brown       fox jumps", "%*s%n%*s%n%*s%n", &a, &b, &c);
printf("%d %d %d\n", a, b, c);

10 17 27, .

, , sscanf sscanf. &cmd[n] cmd+n, n.

+2

ISO 9899 7.19.6.2p12:

n ~~ .    , ,    fscanf.   % n ,    fscanf. ,    . ,    , .

+1

Source: https://habr.com/ru/post/1688334/


All Articles