-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;
};
什麼你嘗試到目前爲止,什麼樣的輸入,預期的結果和收到的結果? –
我無法弄清楚那部分的邏輯。 – shashankgaurav
你可以發佈一個給定的輸入字符串的例子,你期望得到什麼? – NirMH