C++ 使用堆栈确定表达式是否有平衡圆括号

C++ 使用堆栈确定表达式是否有平衡圆括号,c++,stack,C++,Stack,我正在完成这学期的最后一个学校作业,我们第一次被介绍到stacks,但是我的程序没有正确分析表达式,我遇到了一个问题。一切都会执行,但程序总是会产生表达式不平衡的结果。有什么线索能给我指明正确的方向吗 // // main.cpp // Balanced Parenthesis #include "StringStack.h" #include <iostream> using namespace std; int main () { StringStack stac

我正在完成这学期的最后一个学校作业,我们第一次被介绍到stacks,但是我的程序没有正确分析表达式,我遇到了一个问题。一切都会执行,但程序总是会产生表达式不平衡的结果。有什么线索能给我指明正确的方向吗

//    
//  main.cpp
//  Balanced Parenthesis
#include "StringStack.h"
#include <iostream>
using namespace std;


int main ()
{
StringStack stack;
char entry;
    int parCounter = 0;
cout << "This program will accept a string and determine whether it has balanced        parenthesis.\n";
cout << "Please type a sentence to be analyzed\n";

while (cin.get (entry) && entry != '\n')
{
            stack.push(entry);

}
if (stack.isEmpty()) {
    cout << "The stack is empty./n";
}

else{
    stack.pop(entry);
    if (entry == ')') {
        parCounter++;
    }
    else if(entry == '('){
        parCounter--;
    }


}
if (parCounter > 0 || parCounter < 0){
            cout << "This expression has UNBALANCED parentheses\n";
        }
        else
        {
            cout << "This expression has BALANCED parentheses\n";

    }



return 0;
}

//  StringStack.h
//  Balanced Par

#include <iostream>
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 &);
    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 &letter)
{
if (isEmpty())
{
    cout << "The stack is empty.\n";
    exit(1);
}
else
{
    letter = stackArray[top];
    top--;
}
}
//
//main.cpp
//平衡圆括号
#包括“StringStack.h”
#包括
使用名称空间std;
int main()
{
字符串堆栈;
字符输入;
int-parCounter=0;

cout您没有在任何地方初始化或设置成员
stackSize
。这会导致
new char[stackSize]
未定义行为,任何情况都可能发生


修复后,您只需检查堆栈的顶部。您需要围绕
parCount
-控制
if
运行一个循环,直到堆栈为空。

您不应该使用堆栈来存储整个输入字符串本身。您的算法可以改进。因为这是您的任务,我将让您你仔细想想。StringStack::isBalanced方法的定义在哪里?另一方面,你有相同数量的“(”和“)”并不能保证括号的平衡。我建议你阅读一些关于中缀和后缀表达式的文档,然后重写你的代码,以便以正确的方式完成。