sscanf_s读取以“|“为分隔符的字符串时怎么写才能成功

7 篇文章 0 订阅

今天遇到个很坑的问题,如题以"|"为分割符的字符串读取到变量

sscanf_s(buf.c_str(), "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]", temp1, temp2,temp3,temp4,temp5); //报错

这行就一直报错说写入错误…也改过很多版本

sscanf_s(buf.c_str(), "%[^|]%*c%[^|]%*c%[^|]%*c%[^|]%*c%[^|]", temp1, temp2,temp3,temp4,temp5); //报错
sscanf_s(buf.c_str(), "%s|%s|%s|%s|%s", temp1, temp2,temp3,temp4,temp5); //报错

看到stackoverflow里的问题解释,学习了一下通配符的含义

sscanf(str, "%*[^=]%*c%[^&]%*[^=]%*c%s", buf1, buf2);

It’s pretty cryptic, so here’s the summary: each % designates the start of a chunk of text.
If there’s a * following the %, that means that we ignore that chunk and don’t store it in one of our buffers.
The ^ within the brackets means that this chunk contains any number of characters that are not the characters within the brackets (excepting ^ itself).
%s reads a string of arbitrary length, and %c reads a single character.

翻译即:

  • "%" 代表字符串的开头
  • "%*" 代表忽略这段,不存到buffer中
  • [^] 代表读取字符串直到遇到^后面的符号,比如 "[^|]“表示读取字符串遇到”|"就停止读取
  • %s 这尼玛最常用的,就代表字符串
  • %c 代表读取一个字符到buffer

但这时我还没注意到 stackoverflow中他们用的都是sscanf,不是sscanf_s

区别他妈的就在这个_s上,最后搞到凌晨一点搜了下sscanf_s的用法才恍然大悟… _s的表现在哪里,就是要传buffer长度作为参数传进去才行!!!

char temp1[256] = { 0 };
char temp2[256] = { 0 };
char temp3[256] = { 0 };
char temp4[256] = { 0 };
char temp5[256] = { 0 };
        
int ret = sscanf_s(buf.c_str(), "%[^|]|%[^|]|%[^|]|%[^|]|%[^|]", temp1, _countof(temp1), temp2, _countof(temp2),temp3, _countof(temp3));

注:
_countof,Windows宏,用来计算一个静态分配的数组中的元素的个数

_TCHAR arr[20];
sizeof(arr) = 40 bytes
_countof(arr) = 20 elements
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路途遥远gg

帮到你了就好

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值