2014-03-03 134 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]與堆棧頂部的任何內容進行比較。