#include #include #include // ================================================================================ // Class TStringExpr is designed to contain a string with expression to evaluate. // An element of this class allows to // 1. read an expression from an input stream (e.g. cin>>expr; ) // 2. print the expression to an output stream (e.g. cout<>ch; ) // 4. return the read character to the expression (e.g. expr<0) expr[--cur]=ch; }; char get() { return cur0) cur--; }; void print_wrong_char(char *fname); // friend operators 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; } // ================================================================================ int eval_expr(TStringExpr &e); int eval_factor(TStringExpr &e) { char ch; int res; if( e>>ch ){ if( isdigit(ch) ){ e.unget(); e>>res; } else if( ch == '-' ) res = -eval_expr(e); else if( ch == '(' ){ res = eval_expr(e); if( (e>>ch) != ')' ){ e.print_wrong_char("eval_factor"); exit(1); } } } else{ e.print_wrong_char("eval_factor"); exit(1); } return res; } int eval_term(TStringExpr &e) { int left_factor; char ch; left_factor = eval_factor(e); switch( e>>ch ){ case '*': left_factor *= eval_term(e); break; case '/': left_factor /= eval_term(e); break; case '+': case '-': case ')': e.unget(); case 0: break; default: e.print_wrong_char("eval_term"); exit(1); } return left_factor; } int eval_expr(TStringExpr &e) { int left_term; char ch; left_term = eval_term(e); switch( e>>ch ){ case '+': left_term += eval_expr(e); break; case '-': left_term -= eval_expr(e); break; case ')': e.unget(); case 0: // there is nothing more in the string break; default: e.print_wrong_char("eval_expr"); exit(1); } return left_term; } void main() { TStringExpr e; cout<<"Expression to evaluate: "; cin>>e; cout<