#include <cstdio>#include<iostream>#include<cstring>#include<cmath>#include<string>#include<cstdlib>#include<stdio.h>#include<algorithm>#include<stack>using namespacestd;classcalc{Private: Char*expression; enumtoken {OPAREN,ADD,SUB,MULTI,DIV,EXP,CPAREN,VALUE,ENL}; voidBINARYOP (token op, stack<int> &datastack);//Token Getop (int&value);// Public: Calc (Char*s); ~calc () {Delete[] expression;} intresult ();}; Calc::calc (Char*s) {Expression=New Char[Strlen (s) +1]; strcpy (expression,s);} Calc::token Calc::getop (int&value) {Value=0; while(*expression) { while(*expression && *expression = =' ') ++expression; if(*expression >='0'&& *expression <='9') { while(*expression >='0'&& *expression <='9') {Value= value *Ten+ (*expression)-'0'; Expression++; } returnVALUE; } Switch(*expression) { Case '(': expression++;returnOparen; Break; Case ')': expression++;returnCparen; Break; Case '+': expression++;returnADD; Break; Case '-': expression++;returnSUB; Break; Case '*': expression++;returnMULTI; Break; Case '/': expression++;returnDIV; Break; Case '^': expression++;returnEXP; Break; default: Break; } } returnENL;}voidCALC::BINARYOP (token op, stack<int> &datastack) { intnum2 =Datastack.top (); Datastack.pop (); intNUM1 =Datastack.top (); Datastack.pop (); Switch(OP) { CaseADD:datastack.push (NUM1+NUM2); Break; CaseSUB:datastack.push (NUM1-NUM2); Break; CaseMULTI:datastack.push (NUM1*NUM2); Break; CaseDIV:datastack.push (NUM1/NUM2); Break; CaseEXP:datastack.push (POW (num1,num2)); Break; default: Break; }}intCalc::result () {token nextop,topop; Stack<token>Opstack; Stack<int>Datastack; intResultvalue; intCurrentValue; while(1) {CurrentValue=0; Nextop=getop (CurrentValue); if(NEXTOP==ENL) Break; Switch(nextop) { CaseVALUE:datastack.push (CurrentValue); Break; CaseOPAREN:opstack.push (Oparen); Break; CaseEXP:opstack.push (EXP); Break; CaseADD: CaseSUB: while(! (Opstack.empty ()) && (Topop=opstack.top ())! =Oparen) {BINARYOP (Opstack.top (), datastack); Opstack.pop (); } opstack.push (nextop); Break; CaseMULTI: CaseDIV: while(! (Opstack.empty ()) && (topop= opstack.top ())!=oparen && topop>=MULTI) {BINARYOP (Opstack.top (), datastack); Opstack.pop (); } opstack.push (nextop); Break; CaseCparen: while(! (Opstack.empty ()) && (Topop = Opstack.top ())! =Oparen) {BINARYOP (topop,datastack); Opstack.pop (); } opstack.pop (); Break; default: Break; } } while(!Opstack.empty ()) {BINARYOP (Opstack.top (), datastack); Opstack.pop (); } returndatastack.top ();}Chardata[101000];intMain () {scanf ("%s", data); Calc tmp (data); cout<<Tmp.result (); GetChar (); GetChar (); return 0;}
Simple calculator (but you have to make sure the input is legal yo)