I'm currently studying data structures, and I'm trying to code a C ++ program that uses an array as a modeled stack. The code should work as follows:
The user enters a Postfix expression. The expression is read from left to right. Anytime a number is read, it gets a “pop up” on the simulated stack. When the operand is read, the upper two numbers in the simulated stack are “popped”, the operand performs a calculation with these numbers, and the received answer is “returned” back to the simulated stack. The process continues until only one number remains in the simulated stack. This number is a response to the Postfix expression, and it is read on the screen to the user.
I have code (below) that works, for the most part. However, if one of the values in my simulated stack is greater than or equal to 128, this number seems to be stored incorrectly (for example, +128 becomes -128).
What am I doing wrong? Does this have anything to do with how I return an answer in a function calc? In particular, this line of code:return answer;
Any help or tips would be greatly appreciated.
#include <string>
#include <iostream>
using namespace std;
#define SIZE 50
char stack[SIZE];
int top = -1;
void push(char elem)
{
top++;
stack[top] = elem;
}
char pop()
{
char answer;
answer = stack[top];
top--;
return (answer);
}
double calc(char op)
{
int num1, num2, answer;
num1 = pop();
num2 = pop();
switch (op)
{
case '*':
answer = num2 * num1;
break;
case '/':
answer = num2 / num1;
break;
case '+':
answer = num2 + num1;
break;
case '-':
answer = num2 - num1;
break;
default:
cout << "Invalid expression!";
}
push(answer);
return answer;
}
int main ()
{
string postfix;
int solution;
cout << "Please enter a Postfix expression, with operators and operands separated by spaces and/or commas (e.g: 3 7 5 + 2 - * 16 4 + 10 / /): \n";
getline(cin,postfix);
if (postfix.find('/') == 0 || postfix.find('*') == 0 || postfix.find('+') == 0 || postfix.find('-') == 0)
{
cout << "Sorry, that an invalid Postfix expression, and it can't be evaluated.";
return 0;
}
for(unsigned int i = 0; i < postfix.length(); i++)
{
if(postfix[i] == ' ' || postfix[i] == ',')
{
continue;
}
else if(isalnum(postfix[i]))
{
int operand = 0;
while(i < postfix.length() && isalnum(postfix[i]))
{
operand = (operand * 10) + (postfix[i] - '0');
i++;
}
i--;
push(operand);
}
else
{
calc(postfix[i]);
}
}
solution = pop();
cout << "The solution to the Postfix expression is: " << solution;
}
source
share