在抛出"std::out_of_range"实例后终止调用

terminate called after throwing an instance of 'std::out_of_range'

本文关键字:调用 实例 终止 range out std of      更新时间:2023-10-16

在抛出"std::out_of_range"实例后调用

what(): basic_string::替换

嗨,伙计们。我想知道您是否可以帮助我以粗体找出错误。我正在制作一个解释加法和乘法表达式的程序(允许使用括号)。它使用递归,但没有特殊的数据结构。无论如何,我不相信我需要发布整个程序。它正在编译,我正在使用表达式"5*3"对其进行测试,该表达式应返回字符串"15"。出于某种原因,当我对字符串使用 replace() 函数时,我收到越界错误。我想知道您是否知道为什么基于以下代码片段。任何帮助非常感谢。

size_t firstast = eq.find_first_of('*'); // position of first asterisk 
    if (firstast != std::string::npos) {
        // Set num1 and num2 equal to the respective numbers to the left and right of the asterisk:
        std::string num1, num2; 
        size_t num1begin(firstast), num2end(firstast);
        while (isdigit(eq[--num1begin])) 
            num1.insert(0, 1, eq[num1begin]);
        while (isdigit(eq[++num2end]))
            num2.push_back(eq[num2end]);
        // Replace the space of the multiplication equation num1*num2 with its evaluation:
        eq.replace(num1begin, num2end - num1begin + 1, multStrs(num1, num2));
        evaluate_equation(eq);
    }

一个错误在这里:

while (isdigit(eq[--num1begin])) 
  num1.insert(0, 1, eq[num1begin]);

如果字符串以紧跟*的数字开头,这将测试eq[-1]并且没有定义。

您可以将[]运算符调用替换为 .at(),以可靠的方式显式显式错误(但这不会解决任何问题 - 它仅用于练习)。

此外,下一个while可能在数组末尾存在相同/镜像的问题(即使我希望std::string的大多数实现都是秘密地零终止的 - 但不要假设这一点,永远不会)。

相关文章: