Write a program in C++ that evaluates portfix strings (one per line in a text file) with the following restrictions on the input: Each character is either an operand- if it is a digit and the floating point value associated with the digit, or it is one of the 5 binary operators: +, -, *, / (floating point), ^ (exponentiation). You must use a stack, in particular, the linked list implementation of the stack.
Right now Im just tryna get postfix strings with 3 characters like 42-, 23+, 32^, 12*, and 93/. Only my subtraction works. I need to convert the characters into floats but I dont know how to do that and I cant find it in any books.
Code:#include<iostream> #include<cstdio> #include<cmath> #include<string> using namespace std; const int DefaultListSize =50; typedef float Elem; class Link { public: Elem element; /*Value for this node*/ Link* next; /*Pointer to the next node in list*/ Link(const Elem& elemval, Link* nextval =NULL) { element = elemval; next = nextval; } Link(Link* nextval =NULL) { next = nextval; } }; class Lstack { private: Link*top; /*Pointer to first element*/ int size; /*Count number of elements*/ public: Lstack(int sz =DefaultListSize) {top = NULL; size = 0;} ~Lstack() {clear();} /*Destructor*/ void clear() { while (top != NULL) { /*Delete link nodes*/ Link*temp = top; top = top->next; delete temp; } size = 0; } bool push(const Elem& item) { top = new Link(item,top); size++; return true; } bool pop(Elem& item) { if(size == 0) return false; item = top->element; Link*ltemp = top->next; delete top; top = ltemp; size--; return true; } bool topValue(Elem& it) const { if (size ==0) return false; it = top->element; return true; } int length() const {return size;} bool isEmpty() const { if (top == NULL) return true; else return false; } }; bool Operand(float ch){ if(('0' <= ch) && (ch <= '9')) return true; else return false; } bool Operator(char ch){ if((ch == '+') || (ch =='-')|| (ch == '*') || (ch == '/') || (ch == '^')) return true; else return false; } float Eval(float oprndL, char oper, float oprndR); int main(){ Lstack S; string s; float a = 0; char b = 0; float c = 0; float answer; unsigned int i; cout << "Enter Postfix string:\n"; getline(cin, s); for(i=0; i < s.length(); i++ ){ if(s.at(i) != EOF){ if(Operand(s.at(i))){ S.push(s.at(i)); } else if(Operator(s.at(i))){ b = s.at(i); } } } if(!S.isEmpty()){ S.pop(c); S.pop(a); Eval(a, b, c); S.push(Eval(a, b, c)); S.pop(answer); cout << answer << endl; } return 0; } float Eval(float oprndL, char oper, float oprndR){ if(oper == '+') return oprndL + oprndR; else if(oper == '-') return oprndL - oprndR; else if(oper == '*') return oprndL * oprndR; else if(oper == '/') return oprndL / oprndR; else if(oper == '^') return pow(oprndL,oprndR); else return 0.0; }



LinkBack URL
About LinkBacks


