题目要求:分隔符匹配(){} []
main.cpp
#include<iostream>
#include<cstring>
#include"Stack.h"
#include<fstream>
using namespace std;
int ifdelimiter(char a)
{
if(a=='('||a=='['||a=='{')
return 1;
else
if(a==')'||a==']'||a=='}')
return 2;
else
if(a=='/')
return 3;
else
if(a=='*')
return 4;
else
return 0;
}
void main()
{
int examine(Stack <char> s2,char a);
int check=1,a=0;
Stack <char> s1(50);
char x,y,z;
char str[20];
fstream in;
cout<<"输入文件路径"<<endl;
cin>>str;
in.open(str,ios_base::in);
if (in.fail())
{
cout<<"文件打开失败"<<endl;
return ;
}
if(in)
{
while(!in.eof()&&check==1)
{
x=ifdelimiter(z=in.get());
switch(x)
{
case 0:break;
case 1:s1.Push(z);break;
case 2:if(examine(s1,z))
{
s1.Pop();
break;
}
else
{
check=0;
break;
}
case 3:if(!in.eof())
y=in.get();
else
break;
if(y=='*')
{
while(!in.eof())
{
if(in.get()=='*')
;
else
continue;
if(in.get()=='/')
{a=1;break;}
else
continue;
}
if(!a)
check=0;break;
}
else
{x=ifdelimiter(y);}
case 4:if(!in.eof())
y=in.get();
else
break;
if(y=='/')
{
check=0;
break;
}
else
{x=ifdelimiter(y);}
}
}
if(s1.Isempty()==false)
check=0;
}
else
cout<<"Error:Can't open the file."<<endl;
in.close();
if(check)
cout<<"此文件符合分隔符匹配"<<endl;
else
cout<<"此文件不符合分隔符匹配"<<endl;
}
int examine(Stack <char> s2,char a)
{
if(s2.Isempty()==false&&(a==']'&&s2.Top()=='[')||(a==')'&&s2.Top()=='(')||(a=='}'&&s2.Top()=='{'))
return 1;
else
return 0;
}
Stack.h
template <class T>
class Stack
{
private:
int mSize; //栈中最多可存放的元素个数
int top; //栈顶位置,应小于mSize
T *st; //存放栈元素的数组
public:
Stack(int size){mSize=size;top=-1;st=new T[mSize];}//构造函数
~Stack(){top=-1;}//析构函数
bool Pop();//出栈函数
bool Push(const T item);//入栈函数
T Top();//返回栈顶值
bool Isempty();//检查是否为空栈
int Size();//返回栈的大小
};
template <class T>
bool Stack<T>::Isempty()
{
if(top==-1)
return true;
else
return false;
}
template <class T>
int Stack<T>::Size()
{return top+1;}
template <class T>
bool Stack<T>::Push(const T item)
{
if(top==mSize-1)
{
cout<<"栈满溢出"<<endl;
return false;
}
else
{
st[++top]=item;
return true;
}
}
template <class T>
bool Stack<T>::Pop()
{
T item;
if(top==-1)
{
cout<<"栈为空"<<endl;
return false;
}
else
{
item=st[top--];
return true;
}
}
template <class T>
T Stack<T>::Top()
{
T item;
if(top==-1)
cout<<"栈为空"<<endl;
else
{
item=st[top];
return item;
}
}