【问题标题】:C - sscanf not workingC - sscanf 不工作
【发布时间】:2011-10-25 09:05:08
【问题描述】:

我正在尝试使用sscanf从字符串中提取一个字符串和一个整数:

#include<stdio.h>

int main()
{
    char Command[20] = "command:3";
    char Keyword[20];
    int Context;

    sscanf(Command, "%s:%d", Keyword, &Context);

    printf("Keyword:%s\n",Keyword);
    printf("Context:%d",Context);

    getch();
    return 0;
}

但这给了我输出:

Keyword:command:3
Context:1971293397

我期待这个输出:

Keyword:command
Context:3

为什么sscanf 会这样?提前感谢您的帮助!

【问题讨论】:

  • 您是否有充分的理由不检查sscanf 的结果?

标签: c scanf


【解决方案1】:

sscanf 期望 %s 标记以空格分隔(制表符、空格、换行符),因此字符串和 : 之间必须有一个空格

对于外观丑陋的黑客,您可以尝试:

sscanf(Command, "%[^:]:%d", Keyword, &Context);

这将强制令牌与冒号不匹配。

【讨论】:

  • 你的意思是,我不能用“:”作为分隔符?
  • 所以无法从 "command:3" 中提取字符串和整数?
  • 是的,另一端是:sscanf(Command, "%7s:%d", Keyword, &amp;Context);,它只接受 7 个字符长的命令。
  • @John,它正在工作,我想知道为什么:D 你能解释一下吗?非常感谢。
  • [] 的内容表示要匹配的字符。如果 [] 中的第一个字符是 ^,它告诉函数匹配所有 除了 [] 中的字符
【解决方案2】:

如果您不特别喜欢使用 sscanf,则始终可以使用 strtok,因为您想要对字符串进行标记。

    char Command[20] = "command:3";

    char* key;
    int val;

    key = strtok(Command, ":");
    val = atoi(strtok(NULL, ":"));

    printf("Keyword:%s\n",key);
    printf("Context:%d\n",val);

在我看来,这更具可读性。

【讨论】:

    【解决方案3】:

    在此处使用%[ 约定。见scanf手册页:http://linux.die.net/man/3/scanf

    #include <stdio.h>
    
    int main()
    {
        char *s = "command:3";
        char s1[0xff];
        int d;
        sscanf(s, "%[^:]:%d", s1, &d);
        printf("here: %s:%d\n", s1, d);
        return 0;
    }
    

    它给出“here:command:3”作为它的输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 2020-09-10
      • 2016-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多