#include #include #include // ========================================================================================= class TStringExpr { private: string expr; unsigned int cur; public: TStringExpr() { expr=""; cur=0; }; TStringExpr(char *str) { expr=str; cur=0; }; TStringExpr(const string &str) { expr=str; cur=0; }; string operator=(char *str); string operator=(const string &str); void putback(char ch) { if(cur>0) expr[--cur]=ch; }; char get() { return cur0) cur--; }; void print_wrong_char(char *fname); // ---------------- friend istream& operator>>(istream &inp, TStringExpr &e); friend ostream& operator<<(ostream &out, const TStringExpr &e); friend char operator>>(TStringExpr &e, char &ch); friend TStringExpr& operator>>(TStringExpr &e, int &value); }; string TStringExpr::operator=(char *str) { expr = str; cur = 0; return expr; } string TStringExpr::operator=(const string &str) { expr = str; cur = 0; return expr; } void TStringExpr::print_wrong_char(char *fname) { cerr<>(istream &inp, TStringExpr &e) { char ch; e.expr = ""; ch = inp.get(); while( !inp.eof() && ch!='\n' ){ if( ! isspace(ch) ) e.expr += ch; ch = inp.get(); } e.cur = 0; return inp; } ostream& operator<<(ostream &out, const TStringExpr &e) { out<>(TStringExpr &e, char &ch) { if( e.cur < e.expr.length() ) return ch=e.expr[e.cur++]; else return 0; } TStringExpr& operator>>(TStringExpr &e, int &value) { char ch; value = 0; while( ch=e.get() ) if( isdigit(ch) ) value = 10*value + (ch-'0'); else{ e.unget(); break; } return e; } // ========================================================================================= /* ------------------------------------- Grammar: epression ::= term term + expression term - expression term ::= factor factor * term factor / term factor ::= number - factor ( expression ) ------------------------------------- */ int eval_expr(TStringExpr &expr); int eval_factor(TStringExpr &expr) { int res; char ch; if( expr>>ch ) if( ch=='(' || ch=='-' || isdigit(ch) ){ if( ch == '(' ){ res = eval_expr(expr); if( !(expr>>ch) || ch != ')' ){ expr.print_wrong_char("eval_factor()"); exit(1); } } else if( ch == '-' ){ res = - eval_factor(expr); } else{ expr.unget(); expr>>res; } } else{ expr.print_wrong_char("eval_factor()"); exit(1); } return res; } int eval_term(TStringExpr &expr) { char ch; int left, right; left = eval_factor(expr); cerr<<"eval_term(): left = "<>ch ){ if( ch=='*' || ch=='/' ){ right = eval_factor(expr); cerr<<"eval_term(): right = "<>ch ){ expr.print_wrong_char("evaluate()"); exit(1); } return res; } int eval_expr(TStringExpr &expr) { char ch; int left, right; left = eval_term(expr); cerr<<"eval_expr(): left = "<>ch ){ if( ch=='+' || ch=='-' ){ right = eval_term(expr); cerr<<"eval_expr(): right = "<>expr; cout<<"Evaluating '"<