2014-03-03 131 views
0

我有这个算法检查是否平衡的括号字符串的问题。我必须从一个文本文件的输入,并显示在另一个文本文件的输出。我有与此algorithm.Please麻烦帮我找出问题括号平衡与否!在C + +

#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; 
} 
+0

请修复您的代码布局。并发布一个示例来说明什么是错误的。 – hivert

+1

你卡在哪个部分?意外的结果?你有没有尝试使用步进器进行调试? – Steve

+0

你的约束是什么?你的括号什么时候平衡? – user1767754

回答

1

我可以比较肯定,这个说:

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

是不正确的,因为它永远是假的。我假设你的意思是这样的:

if ((c.Top() == '(' && str[i] == ')' || ...) 
0

,因为你比较STR [1]对自己,希望它是两个不同的值,您的代码将永远不会叫“流行”的那一刻,。

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