Brief Description: User enter an expression such as "1+3+(2*5)" and the result is displayed i.e. 14.
Here the code i managed to get so far with the help of a friend:
It is for a homework and it's need to be of recursive type.Code:#include<iostream> #include<sstream> #include<string> #include<cctype> #include<cmath> using namespace std; enum {PLUS='+',MINUS='-',MUL='*',DIV='/'}; double Value_Of_Num(string &Expr) { istringstream is(Expr); double value=0.0; is >> value; return value; } double Value_Of_Expr(string &Expr) { int i=0,p=0,pos_mul=0,pos_div=0; if(Expr.at(0)=='('&&Expr.at(Expr.length()-1)==')') { for(;i<Expr.length();i++) { if(Expr.at(i)=='(') p++; else if(Expr.at(i)==')') p--; if(p==0) break; } if(i==Expr.length()-1) return Value_Of_Expr(Expr.substr(1,Expr.length()-2)); } for(;i<Expr.length();i++) { if(Expr.at(i)=='(') p++; else if(Expr.at(i)==')') p--; else if(p==0&&ispunct(Expr.at(i))) { switch(Expr.at(i)) { case PLUS: return Value_Of_Expr(Expr.substr(0,i))+Value_Of_Expr(Expr.substr(i+1,Expr.length()-i-1)); case MINUS: return Value_Of_Expr(Expr.substr(0,i))-Value_Of_Expr(Expr.substr(i+1,Expr.length()-i-1)); case MUL: pos_mul=i; break; case DIV: pos_div=i; break; } } } if(pos_mul) return Value_Of_Expr(Expr.substr(0,pos_mul))*Value_Of_Expr(Expr.substr(pos_mul+1,Expr.length()-pos_mul-1)); if(pos_div) return Value_Of_Expr(Expr.substr(0,pos_div))/Value_Of_Expr(Expr.substr(pos_div+1,Expr.length()-pos_div-1)); return Value_Of_Num(Expr); } int main() { string expression; cout <<"Enter your expression:"; cin >> expression; cout << Value_Of_Expr(expression)<<endl; return 0; }
The code above work @ 100% but I need to implement the following additional features:
> Able to compute negative numbers
> Multiple brackets such as "((1+3) +(9/3))*2)
PLZ PLZ HELP - Any suggestions or corrections in the code above will be greatly appreciated.



LinkBack URL
About LinkBacks


