博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
这次栽倒在sscanf函数上------ 看看错误的语句:int nRet = sscanf(“xxx=yyy“, “%s=%s“, szKey, szValue);
阅读量:4142 次
发布时间:2019-05-25

本文共 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/

你可能感兴趣的文章
《融入动画技术的交互应用》主题博文推荐
查看>>
链睿和家乐福合作推出下一代零售业隐私保护技术
查看>>
Unifrax宣布新建SiFAB™生产线
查看>>
艾默生纪念谷轮™在空调和制冷领域的百年创新成就
查看>>
NEXO代币持有者获得20,428,359.89美元股息
查看>>
Piper Sandler为EverArc收购Perimeter Solutions提供咨询服务
查看>>
RMRK筹集600万美元,用于在Polkadot上建立先进的NFT系统标准
查看>>
JavaSE_day14 集合中的Map集合_键值映射关系
查看>>
异常 Java学习Day_15
查看>>
Mysql初始化的命令
查看>>
MySQL关键字的些许问题
查看>>
浅谈HTML
查看>>
css基础
查看>>
Servlet进阶和JSP基础
查看>>
servlet中的cookie和session
查看>>
过滤器及JSP九大隐式对象
查看>>
软件(项目)的分层
查看>>
菜单树
查看>>
Servlet的生命周期
查看>>
JAVA八大经典书籍,你看过几本?
查看>>