托架检查器。需要帮助才能添加功能

时间:2014-07-24 11:18:34

标签: c++

我在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;
};

1 个答案:

答案 0 :(得分:0)

好吧,您可以修改StackX类中的std :: vector,以包含括号的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;
  }

}