I was given an assignment to write a program that evaluates a postfix expression using the stack.
I wrote the program and it seems to be working for the most part, however it is having issues determining whether the expression is valid.
Here are the basic steps that I've done:
- Ask user to input an expression (store as string)
- Iterate through each char and determine if the char is an operand, operator, space, or invalid character
- if(char == operand) push onto stack
- if(char == operator) pop twice and do arithmetic then push result onto stack
- Outside of loop, if(!stack.empty()) result == stack.top, stack.pop
- else invalid expression
So the above works well if the stack is empty already, but if there are more operands on the stack the result simply prints out. This is obviously incorrect because it should be an invalid expression if there are multiple operands still on the stack.
I was thinking I should do a while(!stack.empty()) result = stack.top, stack.pop()
however, this would still have the same issue.
Can someone tell me how I should be testing it properly?
Code:
int main()
{
string expression;
char response;
int result = -1; //result of expression. Initialized to -1
Stack stack;
printMenu();
do {
cout << "Would you like to enter an expression? (y / n)" << endl;
cin >> response;
response = toupper(response);
switch(response)
{
case 'Y':
//needed due to new line
cin.ignore();
doWork(stack, expression, result);
break;
case 'N':
cout << "Exiting program." << endl;
break;
default:
cout << "Invalid response. Try again." << endl;
}
} while(response != 'N');
return EXIT_SUCCESS;
}
doWork (don't worry, it'll be renamed) function:
void doWork(Stack stack, string expression, int result)
{
cout << "Enter a PostFix expression: ";
getline(cin, expression);
for(int i = 0; i < expression.size(); i++)
{
if(expression[i] == ' ') {
//do nothing
} else if(isInteger(expression[i])) {
stack.push(convertChar2Int(expression[i]));
} else if(isOperator(expression[i])) {
// pop last 2 ints from stack and do arithmetic on them
int a = stack.top();
stack.pop();
int b = stack.top();
stack.pop();
// push result onto stack
stack.push(calculate(a, b, expression[i]));
} else {
//cerr : enter different expression
cout << expression[i] << " is an invalid character." << endl;
}
}
//the result should be the top of stack
// THIS IS WHERE MY ISSUE IS
if(!stack.empty()) {
result = stack.top();
stack.pop();
} else {
cout << "Invalid expression." << endl;
}
cout << "Result: " << result << endl;
}