0

我在检查括号字符串是否平衡的算法时遇到了一些问题。我必须从文本文件中获取输入并在另一个文本文件中显示输出。我遇到了这个算法的问题。请帮我找出问题

#include <iostream>
#include <string.h>
#include <fstream>
#include "stack.h"
#include "stack.cpp"
using namespace std;
int main() {
  StackType<char> c;
  ifstream inFile("parentheses.txt");
  ofstream outFile("report.txt");
  int i, N;
  char str[500];
  inFile >> N;
  inFile >> str;
  while (str[i]) {
    for (int i = 0; str[i] != '\0'; i++) {
      if ((str[i] == '(') || (str[i] == '{') || (str[i] == '[')) {
        c.Push(str[i]);
      } else if ((str[i] == ')') || str[i] == '}' || str[i] == ']') {
        if (c.isEmpty() == 1)
          outFile << "Parentheses are not Balanced" << endl;
        else if ((str[i] == ')' && str[i] == '(') ||
                 (str[i] == '}' && str[i] == '{') ||
                 (str[i] == ']' && str[i] == '[')) {
          c.Pop();
        } else
          outFile << "Parentheses are not Balanced" << endl;
      }
    }
    i++;
  }
  if (c.isEmpty() == 1)
    outFile << "Parentheses are Balanced" << endl;
  else
    outFile << "Parentheses are not Balanced" << endl;
}
4

2 回答 2

1

我可以肯定地说:

if((str[i] == ')' && str[i]  == '(') || (str[i] == '}' && str[i] == '{') || (str[i] == ']' && str[i] == '['))

是不正确的,因为它总是错误的。我假设你的意思是:

if ((c.Top() == '(' && str[i] == ')' || ...)
于 2014-03-03T17:00:29.463 回答
0

您的代码目前永远不会调用“Pop”,因为您将 str[i] 与自身进行比较,期望它是两个不同的值。

相反,您应该将 stri[i] 与堆栈顶部的任何内容进行比较。

于 2014-03-03T17:01:05.073 回答