Note that there are some explanatory texts on larger screens.

plurals
  1. POSeparating a single string into multiple stacks
    text
    copied!<p>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 '%'. </p> <p>The issue I am having is actually separating the string into stacks. My code is as follows:</p> <pre><code>//The evaluate function takes a string containing an arithmetic expression, //evaluates it,and returns its result int evaluate(string exp) { stack&lt;char&gt; parStack; stack&lt;int&gt; numStack; stack&lt;char&gt; opStack; int j = exp.size(); int i=0; char x; //for (i=0; i&lt;j; i++) //{ while (i&lt;j) { if(exp[i] = '(') { parStack.push(exp[i]); cout &lt;&lt; exp[i] &lt;&lt; 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 </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload