我正在尝试使用 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/