2014-07-24 64 views
-4

我在C++中編寫了以下代碼以匹配括號。一切都很好。但是,如果沒有找到匹配的右括號,我想添加一個顯示左括號位置的功能。我能夠爲最後括號做到這一點。我是一個新手程序員。方括號檢查器。需要幫助添加功能

#include "stdafx.h" 
#include<iostream> 
#include<vector> 
#include<string> 
using namespace std; 

class StackX{ 
private: 
    int top; 
    vector<char> stackVect; 
    int maxSize; 

public: 
    StackX(int s): top(-1),maxSize(s){ 
     stackVect.resize(s); 
    } 

    void push(char a){ 
     stackVect[++top]=a; 
    } 

    char pop(){ 
     return stackVect[top--]; 
    } 

    char peek(){ 
     return stackVect[top]; 
    } 

    bool isEmpty(){ 
     return (top==-1); 
    } 

    bool isFull(){ 
     return (top == maxSize-1); 
    } 

}; 

class Matcher{ 
private: 
    string input; 

public: 
    Matcher(string s):input(s){ 
    } 

    int check(){ 
     int length = input.length(); 
     StackX theStack(length); 
     int i=0; 

     while(i<length){ 
      char toInsert = input[i]; 

      if(toInsert=='{'||toInsert=='('||toInsert=='[') 
       theStack.push(toInsert); 

      else if(toInsert=='}'||toInsert==')'||toInsert==']'){ 
       if(theStack.isEmpty()) { 
        cout<<"Error Found at position :: "<<i+1<<endl; 
        return 0; 
       } 
       char toCheck = theStack.pop(); 
       if((toInsert=='}'&&toCheck!='{')|| 
        (toInsert==')'&&toCheck!='(')|| 
        (toInsert==']'&&toCheck!='[') 
        ){ 
         cout<<"Error Found at position :: "<<i+1<<endl; 
         return 0; 
       } 
      } 
      i++; 
     } 
     if(!theStack.isEmpty()){ 
      cout<<"Opening braces not closed. "<<endl; 
      return 0; 
     } 

     cout<<"No error found"<<endl; 
     return 0; 
    } 

}; 

int main(){ 
    string in; 

    cout<<"Input a string to check ::"; 
    cin>>in; 

    Matcher checkString(in); 
    cout<<endl<<endl; 
    checkString.check(); 
    return 0; 
}; 
+0

什麼你嘗試到目前爲止,什麼樣的輸入,預期的結果和收到的結果? –

+0

我無法弄清楚那部分的邏輯。 – shashankgaurav

+0

你可以發佈一個給定的輸入字符串的例子,你期望得到什麼? – NirMH

回答

0

那麼,你可以modifiy在std ::矢量你StackX類包含支架的std::pair<char, int>及其字符串中的位置。如果您發現該堆棧不處理,你可以打印位置後空...

編輯:我已經記住以下(不完整的,但它應該給你一個想法)

#include <pair> 

class StackX 
{ 
private: 
    vector<pair<char, int> > stackVect; 

    void push(char a, int i){ 
    stackVect[++top] = make_pair(a, i) 
    } 

    pair<char, int> pop(){ 
    return stackVect[top--]; 
    } 
} 

// ... 

int check() 
{ 
    // ... 
    if(toInsert=='{'||toInsert=='('||toInsert=='[') 
    theStack.push(toInsert, i); 

    // ... 

    if(!theStack.isEmpty()){ 
    cout << "Opening braces not closed. " << endl; 

    pair<char, int> res = theStack.pop(); 

    cout << "The opening brace \"" << res.first "\" at position " << res.second 
     << " has no corresponding closing brace" << endl; 

    return 0; 
    } 

} 
+0

我不明白,你能解釋一下嗎? – shashankgaurav