今天遇到个很坑的问题,如题以"|"为分割符的字符串读取到变量中
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

本文详细解析了 sscanf_s 函数的正确使用方法,特别是针对带有 _s 的 sscanf_s 在 C++ 中如何正确读取以特定字符分割的字符串,并强调了需要传递缓冲区长度的重要性。
6416

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



