Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing a stack to determine if an expression has balanced parentheses
    primarykey
    data
    text
    <p>I am working on my last school assignment for the semester and we are being introduced to stacks for the first time but I am having an issue with my program not analyzing the expression properly. Everything executes but the program always comes out with the result that expression is unbalanced. Any clues to point me in the right direction?</p> <pre><code>// // main.cpp // Balanced Parenthesis #include "StringStack.h" #include &lt;iostream&gt; using namespace std; int main () { StringStack stack; char entry; int parCounter = 0; cout &lt;&lt; "This program will accept a string and determine whether it has balanced parenthesis.\n"; cout &lt;&lt; "Please type a sentence to be analyzed\n"; while (cin.get (entry) &amp;&amp; entry != '\n') { stack.push(entry); } if (stack.isEmpty()) { cout &lt;&lt; "The stack is empty./n"; } else{ stack.pop(entry); if (entry == ')') { parCounter++; } else if(entry == '('){ parCounter--; } } if (parCounter &gt; 0 || parCounter &lt; 0){ cout &lt;&lt; "This expression has UNBALANCED parentheses\n"; } else { cout &lt;&lt; "This expression has BALANCED parentheses\n"; } return 0; } // StringStack.h // Balanced Par #include &lt;iostream&gt; using namespace std; #ifndef StringStack_h #define StringStack_h //Define our stack class and its contents class StringStack { private: char *stackArray; int stackSize; char top; public: StringStack(); ~StringStack() {delete[] stackArray;} void push(char); void pop(char &amp;); bool isBalanced(); bool isEmpty(); }; #endif //Constructor StringStack::StringStack() { stackArray = new char[stackSize]; top = 0; } //Function to determine if stack is empty. bool StringStack::isEmpty() { if (top == 0) return true; else return false; } //Function to push letters/puncuation onto the stack void StringStack::push(char letter) { //if (isEmpty()) { top++; stackArray[top] = letter; } //else //{ //exit(1); //} } //Function to pop letters/puncuation off the stack void StringStack::pop(char &amp;letter) { if (isEmpty()) { cout &lt;&lt; "The stack is empty.\n"; exit(1); } else { letter = stackArray[top]; top--; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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