您的位置:首页 > 其它

分析算术表达式是否有效(间接递归的例子)

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: