gpt4 book ai didi

c++ - substr 导致段错误

转载 作者:太空宇宙 更新时间:2023-11-04 04:36:55 25 4
gpt4 key购买 nike

我有以下字符串:

B�#012a#016�G�6�)_#014�d%|1401 01 000][M00FEB11002FA]_13:40:39,08-30-2012�:�

我编写了这个简单的代码来获取 | 后面的值 1401

问题是当我调用 substr 时出现段错误,代码是这样的:

string test = "B�#012a#016�G�6�)_#014�d%|1401 01 000][M00FEB11002FA]_13:40:39,08-30-2012�:�";
int jj = test.find("]");


for (int j = jj ; j > 0 ; j--)
{
if (test.at(j) == '|')
{
test = test.substr(j+1);
test = test.substr(0,test.find_first_of(' '));
}
}

有人可以说我做错了什么吗?

最佳答案

The problem is when i call substr i get a segmentation fault the code is this:

没有。段错误是由于您未能处理 at 引发的异常而调用的。因为在您第一次修改字符串后,后续的 at调用将访问字符串边界之外的索引。

如果在字符串修改后保留循环,则它会起作用。

也就是说,通过将整个外循环替换为 string::rfind 可以大大简化代码。 ,并替换两个 substr单个调用:

int end = test.find("]");
int start = test.rfind("|", end);
test = test.substr(start + 1, test.find(' ', start) - start);

(这里也不需要find_first_of。)

关于c++ - substr 导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12195075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com