Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

C++. Postfix expression calculator. Below is code for a postfix expression calculator. The user enters a postfix expression and the program outputs the answer. The

C++. Postfix expression calculator.

Below is code for a postfix expression calculator. The user enters a postfix expression and the program outputs the answer. The output is supposed to look like this:

 Enter postfix expression: 2 3 4 + * The value of the expression is 14 More expressions (Y or N)? Y Enter postfix expression: 7 2 / The value of the expression is 3 More expressions (Y or N)? N

The program also needs error checking for the following:

  • Invalid character in the input expression - If this error occurs, print an error message stating that an invalid character was encountered.
  • Stack is empty when the algorithm needs to remove an operand - This happens when the expression has too many operators or when the operators and operands are not ordered correctly. We call this a malformed expression. If this error occurs, print an error message indicating that the expression is malformed.
  • When the loop in the algorithm ends, there should be exactly one value left on the stack and it is the value of input expression. If the input contained too many operands, there will be more than one value left on the stack. If you remove what should be the result of the expression, the stack should be empty. If it is not, you should print an error message indicating that the expression is malformed.

Here is the code I have so far. Any help would be appreciated!

stack_driver.cpp

#include

#include

#include

#include "ArrayStack.hpp"

#include "StackInterface.hpp"

using namespace std;

//Function to check postfix expression

int checkPostfix(string expression);

//Function to check if character is a digit

bool digit(char ch);

//Function to check if character is operand

bool operand(char ch);

//Function to evaluate expression and return output

int evaluateExpression(char operation, int operand1, int operand2);

int main()

{

//Declare string variable

string expression;

//Loop again variable

char again;

do

{

//Get string from user

cout << "Enter postfix expression: " << endl;

getline(cin, expression);

//Check operators, digits, and spaces

int result = checkPostfix(expression);

//Display result

cout << "The value if the expression is: " << result << endl;

//Ask user if they want to enter another expression

cout << "More expressions? (Y or N)" << endl;

cin >> again;

}

while (again == 'Y');

return 0;

} // end driver

//Function to check postfix expression

int checkPostfix(string expression)

{

//Declare stack

stack Stack;

for(int i = 0; i < expression.length(); i++)

{

//Look at each character

if(expression[i] == ' ' || expression[i] == ',') continue;

//If operand, push the value of the operand ch onto the stack

else if(operand(expression[i]))

{

int operand2 = Stack.top(); Stack.pop();

int operand1 = Stack.top(); Stack.pop();

//EvaluateExpression

int result = evaluateExpression(expression[i], operand1, operand2);

//Push result onn top of stack

Stack.push(result);

}

else if((digit)(expression[i]))

{

//Get digits from the string

int operand = 0;

while(i < expression.length() && digit(expression[i]))

{

//Going left to right, multiply current total by 10 and add the new digit

operand = (operand * 10) + (expression[i] - '0');

i++;

}

//Deincrement i becaise it will be re-incremented again

i--;

//Push operand onto stack

Stack.push(operand);

}

}

//Output of result

return Stack.top();

}

//Function to check if character is a digit

bool digit(char ch)

{

//Return true for numbers 0 through 9

if(ch >= '0' && ch <= '9')

{

return true;

}

//Else return false

else

{

return false;

}

}

//Function to check if character is operand

bool operand(char ch)

{

// Return true for +, -, *, and /

if(ch == '+' || ch == '-' || ch == '*' || ch == '/')

{

return true;

}

//Else return false

{

return false;

}

}

//Function to evaluate expression and return output

int evaluateExpression(char operation, int operand1, int operand2)

{

//Add operation

if(operation == '+')

{

return operand1 + operand2;

}

//Subtract operation

else if(operation == '-')

{

return operand1 - operand2;

}

//Multply operation

else if(operation == '*')

{

return operand1 * operand2;

}

//Division operation

else if(operation == '/')

{

return operand1 / operand2;

}

//Exception

cout << "Error" << endl;

return -1;

}

ArrayStack.hpp

#ifndef ARRAY_STACK_

#define ARRAY_STACK_

#include "StackInterface.hpp"

const int MAX_STACK = 5;

template

class ArrayStack : public StackInterface

{

private:

ItemType items[MAX_STACK]; // Array of stack items

int top; // Index to top of stack

public:

ArrayStack(); // Default constructor

bool isEmpty() const;

bool push(const ItemType& newEntry);

bool pop();

ItemType peek() const;

}; // end ArrayStack

#include // For assert

template

ArrayStack::ArrayStack() : top(-1)

{

} // end default constructor

// Copy constructor and destructor are supplied by the compiler

template

bool ArrayStack::isEmpty() const

{

return top < 0;

} // end isEmpty

template

bool ArrayStack::push(const ItemType& newEntry)

{

bool result = false;

if (top < MAX_STACK - 1) // Does stack have room for newEntry?

{

top++;

items[top] = newEntry;

result = true;

} // end if

return result;

} // end push

template

bool ArrayStack::pop()

{

bool result = false;

if (!isEmpty())

{

top--;

result = true;

} // end if

return result;

} // end pop

template

ItemType ArrayStack::peek() const

{

assert(!isEmpty()); // Enforce precondition

// Stack is not empty; return top

return items[top];

} // end peek

// End of implementation file.

#endif

StackInterface.hpp

#ifndef STACK_INTERFACE_

#define STACK_INTERFACE_

template

class StackInterface

{

public:

/** Sees whether this stack is empty.

@return True if the stack is empty, or false if not. */

virtual bool isEmpty() const = 0;

/** Adds a new entry to the top of this stack.

@post If the operation was successful, newEntry is at the top of the stack.

@param newEntry The object to be added as a new entry.

@return True if the addition is successful or false if not. */

virtual bool push(const ItemType& newEntry) = 0;

/** Removes the top of this stack.

@post If the operation was successful, the top of the stack

has been removed.

@return True if the removal is successful or false if not. */

virtual bool pop() = 0;

/** Returns the top of this stack.

@pre The stack is not empty.

@post The top of the stack has been returned, and

the stack is unchanged.

@return The top of the stack. */

virtual ItemType peek() const = 0;

/** Destroys object and frees memory allocated by object. */

virtual ~StackInterface() { }

}; // end StackInterface

#endif

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Learning PostgreSQL

Authors: Salahaldin Juba, Achim Vannahme, Andrey Volkov

1st Edition

178398919X, 9781783989195

More Books

Students also viewed these Databases questions

Question

What is the difference between a strut and a column?

Answered: 1 week ago