本文共 1318 字,大约阅读时间需要 4 分钟。
之前用sscanf也是得心应手的, 比如:
#include#include 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#include 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#include 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://tfgvi.baihongyu.com/