Question: Please help me to improve this code to be able to modify the Postfix Calculator and read entries from a file, one line at a
Please help me to improve this code to be able to modify the Postfix Calculator and read entries from a file, one line at a time
A postfix expression to be invalid if:
An operation is encountered, but there are not at least two entries on the stack.
The postfix expression has been consumed, but there is not exactly one entry remaining on the stack.
This is my code so far:
#include
struct Stack* createStack(unsigned capacity) { struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
if (!stack) return NULL;
stack->top = -1; stack->capacity = capacity; stack->array = (int*)malloc(stack->capacity * sizeof(int));
if (!stack->array) return NULL;
return stack; }
int isEmpty(struct Stack* stack) { return stack->top == -1; }
char peek(struct Stack* stack) { return stack->array[stack->top]; }
char pop(struct Stack* stack) { if (!isEmpty(stack)) return stack->array[stack->top--]; return '$'; }
void push(struct Stack* stack, char op) { stack->array[++stack->top] = op; } int evaluatePostfix(char* exp) { struct Stack* stack = createStack(strlen(exp)); int i; if (!stack) return -1; for (i = 0; exp[i]; ++i) { if (isdigit(exp[i])) push(stack, exp[i] - '0'); else { int val1 = pop(stack); int val2 = pop(stack); switch (exp[i]) { case '+': push(stack, val2 + val1); break; case '-': push(stack, val2 - val1); break; case '*': push(stack, val2 * val1); break; case '/': push(stack, val2 / val1); break; } } } return pop(stack); }
int main() { ifstream in("Postfix.txt"); int result; char expression[100];
if (!in) { cout << "Cannot open file. "; return 0; }
while (in) { in.getline(expression, 100); if (in) { result = evaluatePostfix(expression); cout << "Result: " << result << endl; } }
in.close();
return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
