#include #include"stack2.h" #include"polynomial.h" using namespace std; int main() { Stack s; char c; Polynomial * v1, * v2, * v3; float coeff; int degree; bool done=false; bool ret; // The loop below reads the input, one operator at a time, // and carries out the operation depending on the operator. // It stops upon receiving 'q' or if the read fails. while (!done) { if (!(cin >> c)) { cout << "Error: cannot read input\n"; break; } switch (c) { case '?': if (!(cin >> coeff)) { // Read the float input cout << "Error: cannot read float coeff\n"; // cin failed to read the float done = true; // so we stop } else if (!(cin >> degree)) { // Read the int input cout << "Error: cannot read int degree\n"; // cin failed to read the float done = true; // so we stop } else if((v1=new Polynomial)==NULL || !v1->AddMonomial(degree, coeff) || !s.Push(v1)) { cout<<"Error!\n"; if (v1!=NULL) delete v1; } break; case '+': // Handle all the arithmetic operators similarly case '-': case '*': if(!s.Pop(v1)) { cout<<"Stack Empty!\n"; break; } if(!s.Pop(v2)) { cout<<"Stack Has Only One Entry!\n"; delete v1; break; } if ((v3=new Polynomial)==NULL) { cout<<"Out of memory!\n"; delete v1; delete v2; break; } // We already know c is an arithmetic operator; // v1 and v2 are the operands // now perform the operation and put the result in v3 switch (c) { case '+': ret=v3->EqualToSum(v2,v1); break; case '-': ret=v3->EqualToDiff(v2,v1); break; case '*': ret= v3->EqualToProd(v2,v1); break; } if (!ret) cout<<"Arithmetic error!\n"; else if (!s.Push(v3)) { cout<<"Stack Overlow!\n"; delete v3; } delete v1; delete v2; break; case '=': // Print the top of the stack by pop-print-push if(!s.Pop(v1)) { cout<<"Stack Empty!\n"; break; } v1->Print(); if(!s.Push(v1)) { cout<<"Stack Overlow!\n"; delete v1; } break; case 'p': // Pop the top if(!s.Pop(v1)) cout<<"Stack Empty!\n"; else delete v1; break; case 'q': // Quit done=true; break; default: cout<<"Invalid Entry!\n"; break; } } // Free up memory by popping everything and deleting it while (s.Pop(v1)) delete v1; return 0; }