之前用sscanf也是得心应手的, 比如:
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- char szLine[100] = {0};
- int left = 0;
- int right = 0;
- strncpy(szLine, "123=456", sizeof(szLine) - 1);
- int nRet = sscanf(szLine, "%d=%d", &left, &right);
- printf("nRet is %d\n", nRet);
- printf("left is %d, right is %d\n", left, right);
- return 0;
- }
#include <stdio.h>
#include <string.h>
int main()
{
char szLine[100] = {0};
int left = 0;
int right = 0;
strncpy(szLine, "123=456", sizeof(szLine) - 1);
int nRet = sscanf(szLine, "%d=%d", &left, &right);
printf("nRet is %d\n", nRet);
printf("left is %d, right is %d\n", left, right);
return 0;
}
结果很正常:
nRet is 2
left is 123, right is 456
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- char szLine[100] = {0};
- char szKey[50] = {0};
- char szValue[50] = {0};
- strncpy(szLine, "xxx=yyy", sizeof(szLine) - 1);
- int nRet = sscanf(szLine, "%s=%s", szKey, szValue);
- printf("nRet is %d\n", nRet);
- if(0 == strcmp(szKey, "xxx"))
- {
- printf("yes, key\n");
- }
- if(0 == strcmp(szValue, "yyy"))
- {
- printf("yes, value\n");
- }
- return 0;
- }
#include <stdio.h>
#include <string.h>
int main()
{
char szLine[100] = {0};
char szKey[50] = {0};
char szValue[50] = {0};
strncpy(szLine, "xxx=yyy", sizeof(szLine) - 1);
int nRet = sscanf(szLine, "%s=%s", szKey, szValue);
printf("nRet is %d\n", nRet);
if(0 == strcmp(szKey, "xxx"))
{
printf("yes, key\n");
}
if(0 == strcmp(szValue, "yyy"))
{
printf("yes, value\n");
}
return 0;
}
结果为:
nRet is 1
从结果看, 解析失败, 为什么呢? 原来此时=并没有做分割符, 而是做了szKey的一部分, 此时szValue仍然是空串。 那该怎么改呢?如下:
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- char szLine[100] = {0};
- char szKey[50] = {0};
- char szValue[50] = {0};
- strncpy(szLine, "xxx=yyy", sizeof(szLine) - 1);
- int nRet = sscanf(szLine, "%[^=]=%[^=]", szKey, szValue);
- printf("nRet is %d\n", nRet);
- if(0 == strcmp(szKey, "xxx"))
- {
- printf("yes, key\n");
- }
- if(0 == strcmp(szValue, "yyy"))
- {
- printf("yes, value\n");
- }
- return 0;
- }
#include <stdio.h>
#include <string.h>
int main()
{
char szLine[100] = {0};
char szKey[50] = {0};
char szValue[50] = {0};
strncpy(szLine, "xxx=yyy", sizeof(szLine) - 1);
int nRet = sscanf(szLine, "%[^=]=%[^=]", szKey, szValue);
printf("nRet is %d\n", nRet);
if(0 == strcmp(szKey, "xxx"))
{
printf("yes, key\n");
}
if(0 == strcmp(szValue, "yyy"))
{
printf("yes, value\n");
}
return 0;
}
结果为:
nRet is 2
yes, key
yes, value
以后还是要小心啊, 定位较长时间, 才发现是栽倒在这个最简单的地方
。
转载自
http://blog.youkuaiyun.com/stpeace/article/details/45725517 我也遇到这种极品问题,目前还在想办法解决。
本文详细探讨了sscanf函数在不同场景下的使用方法及注意事项,通过实例展示了如何正确解析包含键值对的字符串,并进行了错误排查。重点强调了在字符串中使用变量作为分割符的重要性。
2459

被折叠的 条评论
为什么被折叠?



