What I am trying to do is take a string, say “((4+2)/2)”, and evaluate it, returning 3. I am supposed to do this by separating the string into three separate stacks… one for the open parentheses ‘(‘, one for the digits ‘0’ – ‘9’, and one for the operators, ‘+’ ‘-‘ ‘*’ ‘/’ and ‘%’.
The issue I am having is actually separating the string into stacks. My code is as follows:
//The evaluate function takes a string containing an arithmetic expression,
//evaluates it,and returns its result
int evaluate(string exp)
{
stack<char> parStack;
stack<int> numStack;
stack<char> opStack;
int j = exp.size();
int i=0;
char x;
//for (i=0; i<j; i++)
//{
while (i<j)
{
if(exp[i] = '(')
{
parStack.push(exp[i]);
cout << exp[i] << endl; // just to see what is being pushed
}
if((exp[i]='0') || (exp[i]='1') || (exp[i]='2') || (exp[i]='3') || (exp[i]='4') || (exp[i]='5') || (exp[i]='6') || (exp[i]='7') || (exp[i]='8') || (exp[i]='9')) // I feel this is terribly inefficient
{
numStack.push(exp[i]);
}
if((exp[i] = '+') || (exp[i] = '-') || (exp[i] = '*') || (exp[i] = '/') || (exp[i] = '%'))
{
opStack.push(exp[i]);
}
i++;
}
//} // end for
return -1;
} // end evaluate
As you can see, I’ve tried tackling this with both for loops and while loops, both giving the same result. What happens is, for some reason, if I enter “(5+3)”, it prints out “(((((” as what is being pushed. Why is my if statement repeating itself like this? Ignore for now the return -1 at the end, as that will be completed to actually evaluate the string, which I’m sure I can handle, once I can effectively create the stacks.
you should use two “=” in your if statement