分析算术表达式是否有效(间接递归的例子)
2014-04-26 22:34
525 查看
//判断算数表达式是否有效 ( 间接递归的例子 ) //表达式如 a + b | (a + b) | a * (a + b) //把一个表达式(expression) 进行细分 //expression = term + term | term - term | term //term = factor * factor | factor / factor | factor //factor = (expression) | digit | letter #include <iostream> #include <string> using namespace std; class ExpressionJudge { public: bool isValid(const string& expr,const int pos); private: // 检查expr_中从 pos_ 位置开始是否有一个合法的算数表达式 bool ValidExpression(); // 检查expr_中从 pos_ 位置开始是否一个合法的term bool ValidTerm(); // 检查expr_中从 pos_ 位置开始是否是一个合法的factor bool ValidFactor(); // 获取expr_中 pos_ 位置之后的下一个非空白字符 char GetChar(); string expr_; int pos_; }; bool ExpressionJudge::isValid(const string& expr,const int pos) { expr_ = expr; pos_ = pos; return ValidExpression() && (pos_ == expr_.length() - 1) ; } bool ExpressionJudge::ValidExpression() { if( ValidTerm() ) { char c = GetChar(); if( c == '+' || c == '-') { return ValidTerm(); } else { pos_ --; return true; } } return false; } bool ExpressionJudge::ValidTerm() { if( ValidFactor() ) { char c = GetChar(); if( c == '*' || c == '/') { return ValidFactor(); } else { pos_ --; return true; } } return false; } bool ExpressionJudge::ValidFactor() { char c = GetChar(); if(c == '(') { if( ValidExpression() && GetChar() == ')') return true; return false; } return isalnum(c); } char ExpressionJudge::GetChar() { while(1) { ++pos_; if( pos_ == expr_.length() ) return ';' ; char c = expr_[pos_]; if( ! isspace(c) ) return c; } } int main() { ExpressionJudge exprjudge; string expr; while(getline(cin,expr)) { if(expr == "#") break; cout << expr << " is " << ( exprjudge.isValid(expr,-1) ? "Valid" : "inVaild" )<< endl; } return 0; }
相关文章推荐
- 语法分析:算术表达式递归下降分析程序设计
- 语法分析:算术表达式递归下降分析程序设计
- 语法分析:算术表达式递归下降分析程序设计
- 编译原理之算术表达式文法的预测分析算法c实现
- 2147 表达式语法分析——递归子程序法
- 表达式语法分析——递归子程序法
- Atitit 表达式原理 语法分析 原理与实践 解析java的dsl 递归下降是现阶段主流的语法分析方法
- 通过百度外链分析工具分析外链是否有效
- 编译原理之算术表达式的词法分析算法c实现
- 2016年秋季《编译原理》课程实验(2014级)表达式语法分析——递归子程序法
- 语法分析:算术表达式预测分析程序设计
- python实现算术表达式的词法语法语义分析(编译原理应用)
- atof()函数详解----NOI2.2基本算法之递归和自调用函数 逆波兰表达式 分析
- 验证邮箱和手机号码是否有效的正则表达式
- 利用堆栈求解算术表达式 利用递归求解算术表达式
- 编译原理实验2-递归下降分析–表达式求值
- 检查一个算术表达式中的括号是否匹配
- 栈的实现,栈在算术表达式计算中的应用及Java中栈的源码分析
- 关于递归的理解及递归表达式复杂度分析(以求解最大公约数为例)
- 用正则表达式检验是否输入日期时间是有效