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.
Here is what I got so far:
Code:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
const int DefaultListSize =50;
typedef float Elem;
typedef char Link;
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;
};
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;
int main(){
int v;
bool operand(char ch){
if(('0' <= ch) && (ch <= '9'))
return true;
else return false;
}
while(EOF){
if(ch != '/n') if(operand(ch)) S.push(Val(ch));
else {S.pop(oprndR);
S.pop(oprndL);
v = Eval(oprndL,ch,oprndR);
S.push(v);
}
}
else S.pop(answer);
cout<< answer;
return 0;
}
1>------ Build started: Project: Project 2, Configuration: Debug Win32 ------
1> Project 2.cpp
1>c:\users\justin\documents\visual studio 2010\projects\project 2\project 2\project 2.cpp(78): fatal error C1075: end of file found before the left brace '{' at 'c:\users\justin\documents\visual studio 2010\projects\project 2\project 2\project 2.cpp(51)' was matched
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========