首页 > 解决方案 > How can I use a stack to validate if an expression or assignment with BNF in C++?

问题描述

I have tokenized with a space delimiter into a vector and then I have made it into stack. I want to use the stack to validate whether the expression or assignment is correct.

assignment shall have the form: id = exp; expression shall have the form: id op id {op id} -- any length as long as pairs of op and id are added A parenthesis pair may be used to group any id op id combination. Therefore: id op (id op id) op id AND id op id op (id op id) -- valid expressions

标签: c++stackexpressiongrammarbnf

解决方案


你要这个 :-

https://en.wikipedia.org/wiki/Shunting-yard_algorithm

这会将带括号的中缀表达式转换为堆栈上可以评估的后缀表达式。如果分流失败,则表达式无效,即通过适当的检查,您可以将 x=3+((-+) 捕获为格式错误的表达式。


推荐阅读