打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
这次栽倒在sscanf函数上

       之前用sscanf也是得心应手的, 比如:


  1. #include <stdio.h>  
  2. #include <string.h>  
  3.   
  4. int main()  
  5. {  
  6.     char szLine[100] = {0};  
  7.     int left = 0;  
  8.     int right = 0;  
  9.   
  10.     strncpy(szLine, "123=456", sizeof(szLine) - 1);  
  11.     int nRet = sscanf(szLine, "%d=%d", &left, &right);  
  12.     printf("nRet is %d\n", nRet);  
  13.       
  14.     printf("left is %d, right is %d\n", left, right);  
  15.   
  16.     return 0;  
  17. }  

      结果很正常:

nRet is 2
left is 123, right is 456


      现在, 碰到了字符串, 所以我随心所欲地类比写成:
  1. #include <stdio.h>  
  2. #include <string.h>  
  3.   
  4. int main()  
  5. {  
  6.     char szLine[100] = {0};  
  7.     char szKey[50] = {0};  
  8.     char szValue[50] = {0};  
  9.   
  10.     strncpy(szLine, "xxx=yyy", sizeof(szLine) - 1);  
  11.     int nRet = sscanf(szLine, "%s=%s", szKey, szValue);  
  12.     printf("nRet is %d\n", nRet);  
  13.       
  14.     if(0 == strcmp(szKey, "xxx"))  
  15.     {  
  16.         printf("yes, key\n");  
  17.     }  
  18.   
  19.     if(0 == strcmp(szValue, "yyy"))  
  20.     {  
  21.         printf("yes, value\n");  
  22.     }  
  23.   
  24.     return 0;  
  25. }  

       结果为:

nRet is 1


       从结果看, 解析失败, 为什么呢? 原来此时=并没有做分割符, 而是做了szKey的一部分, 此时szValue仍然是空串。 那该怎么改呢?如下:

  1. #include <stdio.h>  
  2. #include <string.h>  
  3.   
  4. int main()  
  5. {  
  6.     char szLine[100] = {0};  
  7.     char szKey[50] = {0};  
  8.     char szValue[50] = {0};  
  9.   
  10.     strncpy(szLine, "xxx=yyy", sizeof(szLine) - 1);  
  11.     int nRet = sscanf(szLine, "%[^=]=%[^=]", szKey, szValue);  
  12.     printf("nRet is %d\n", nRet);  
  13.       
  14.     if(0 == strcmp(szKey, "xxx"))  
  15.     {  
  16.         printf("yes, key\n");  
  17.     }  
  18.   
  19.     if(0 == strcmp(szValue, "yyy"))  
  20.     {  
  21.         printf("yes, value\n");  
  22.     }  
  23.   
  24.     return 0;  
  25. }  

        结果为:

nRet is 2
yes, key
yes, value


       以后还是要小心啊, 定位较长时间, 才发现是栽倒在这个最简单的地方

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
【原创】自制编程语言-5 变量的赋值(1)
字符串的比较
字符匹配strstr小函数
c语言中串比较函数
字符串函数之strcmp
C语言中strcmp的字符串比较
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服