c - scanf 说明符 "n"算什么?

标签 c scanf

作为程序的一部分,我将命令处理为一系列标记。到目前为止我有:

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”很难看,尤其是当有很多参数时。

查看http://www.cplusplus.com/reference/cstdio/scanf/有一个可能的说明符“n”用于检索“到目前为止读取的字符”。不确定在这种情况下“读取”是什么意思,因为字符串中有空格和其他内容,而不是检索到的字符串的一部分; “添加 foo 42”。这就是我希望它工作的方式,但不确定它是否正确:

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...
  }
}

最佳答案

到目前为止读取的字符数包括所有空格:

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);

以上prints 10 17 27,让您在每个扫描点获得缓冲区内的位置。

这非常适合您的用例,因为您可以在进入第二个 sscanf 时跳过第一个 sscanf 中处理的字符数。您可以使用 &cmd[n] 或等效的 cmd+n 来跳过最初的 n 个字符。

关于c - scanf 说明符 "n"算什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46989068/

相关文章:

c - 为什么 C 程序使用 Scanf 给出奇怪的输出?

linux - 如何使用汇编语言从键盘读取输入字符串

c - 无法创建新文件

c - 如何修复 `itoa` 实现,使其不打印反向输出?

c - 为什么 scanf() 在此代码中导致无限循环?

c - 在 scanf() 之后,我如何 "delete"无用

c - 如何使用 sscanf 查找字符串中的小写字母

c - 从文件中读取c代码

c - 如何链接这两个函数

c - C语言中的gets()接受参数