C - sscanf 不工作

标签 c scanf

我正在尝试使用 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 期望 %s 标记以空格分隔(制表符、空格、换行符),因此您必须在字符串和 :

对于一个丑陋的 hack 你可以尝试:

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

这将强制 token 不匹配冒号。

关于C - sscanf 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7887003/

相关文章:

c - select() 和 C 上带有动态缓冲区的非阻塞 recv

c - 为什么 scanf 返回负数时不使用 printf()?

c++ - 与 stdlib system() 函数等效的 Win32 API 是什么?

在程序中检查网络状态和控制PPP

php - 集合中所有可能的组合

C: scanf 输入单字符及校验

c - 使用 sscanf 读取带空格的字符串

c++ - sscanf()的问题不会读取char数组中的每个0

c - 在 C 中使用 fgets 时出错

c - 初始化具有 Union 的 Struct 数组的元素时出现问题