在抛出"std::out_of_range"实例后终止调用
terminate called after throwing an instance of 'std::out_of_range'
在抛出"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
的大多数实现都是秘密地零终止的 - 但不要假设这一点,永远不会)。
相关文章:
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 对象实例化调用构造函数的次数太多
- 如果 std::vector::clear() 不是静态的,如何在没有实例的情况下调用它?
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- C++应用程序 MySQL odbc 数据库连接错误:在引发"otl_tmpl_exception<>"实例后终止调用
- C++中的单例实现在调用 getInstance 函数时不会产生相同的类实例
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 在抛出 'std::runtime_error' 的实例后终止调用 what(): Filebuf 和 ostream 的 I/O 错误
- 从基类实例调用派生类方法而不进行强制转换
- 以下代码如何工作以每次为唯一调用堆栈唯一实例化模板函数?
- 在字符串函数中抛出'char const*'实例后调用的终止
- 如何使用 c++ 从另一个 cpp 文件中的 main.cpp 调用实例化类
- 统一功能使用模板专业化和接口来调用实例和原始类型
- 调用实例化函数时发生链接器错误
- 正在销毁调用实例
- 为什么我可以静态地调用实例函数