c++ - 我的有效表达式检查器中的扭结
问题描述
很明显,我的有效表达式运算符遇到了一些问题。理论上,我理解首先检查范围开启器的概念,如果您看到没有范围开启器的范围更近,那么它是无效的。我不太确定它是我绘制的图表还是什么,但就像我说的那样,在编码时使用算法时我只是有点困惑,有什么提示吗?另外,我的教授告诉我在这里使用案例切换?这对我有什么好处?当实际上我只需要一个 if 语句时,我不需要为范围开启器和关闭器提供 3 个不同的 case 开关吗?
//=============use case switch here
void check_expression(char expression[80], bool& valid)
{
Stack symbStack; //stack to hold scope openers
char symbol, //current symbol in the expression being investigated
top_symb; //current scope opener at the top of the stack
int i = 0; //subscript to element in expression array, initialized to
//first element
valid = true;
symb = expression[i];
while(symb != '\0') //while symbol in expression is not the null terminator
{
if( symbol == '{' || symbol == '[' || symbol == '(' )
{
symbStack.Push(symbol);
}
else if( symbol == '}' || symbol == ']' || symbol == ')' )
{
if(symbStack.IsEmpty())
{
cout << "Expression is invalid!";
valid == false;
}
else
{
top_symb = symbStack.StackTop();
symbStack.Pop();
if( (top_symb == '(' && symbol != ')') ||
(top_symb == '[' && symbol != ']') ||
(top_symb == '{' && symbol != '}') )
{
valid = false;
}
}
}
i++; //incrememt the subscript to the next character in the expression.
symb = expression[i]; //assign symb to the next character in expression.
}
//Check to see if the stack is not empty. If it is not empty, then
//the expression is invalid, in which case you want to assign valid to false
return;
}
解决方案
valid == false;
^^^^
有你的罪魁祸首。摆脱其中一个,=
你应该会很好。
作为旁注,如果您意识到您正在查看无效的表达式,您可以立即返回!在那之后,表达式无法变为有效。因此,您可以return;
在设置valid
为false
.
推荐阅读
- sql-server - SSIS - 遍历按创建顺序排序的文本文件,并将每个文件上的每条记录作为更新或插入到 SQL 表中处理
- bpf - 增加我的 struct char 数组的大小限制以传递更大的字符串
- django - 如何从 django 上的模型实例中获取所有值
- python - 如何使图例显示列表中的所有 str 值?
- regex - 正则表达式 - 如何提取文本的特定部分
- javascript - 需要根据旁边的数据跳过一些数据
- postgresql - 空间数据自连接查询的索引
- css - 如何使用 Shiny 和 Flexdashboard 向应用程序添加 .css 样式?
- windows - 无法将 Tomcat8.5 安装为服务
- node.js - `User` 不是路径 `ref` 的有效类型