#include<iostream> #include <cmath> #include<fstream> #include <stack> #include <list>
using namespace std;// 在VC中c++无法用ios::nocreate,而用.h无法用exit
struct bracket { char bk; int row; int line;
}A={'{',0,0},B={'[',0,0},C={'(',0,0},a={'}',0,0},b={']',0,0},c={')',0,0}; int dis=3;
int main() { stack <bracket, list<bracket> > istack; bracket X; int row=1,line=0;
ifstream infile("f.cpp",ios::in/*|ios::nocreate*/);//定义输入文件流对象,以输入方式打开磁盘文件f.cpp if(! infile) { cout<<"open error!"<<endl; return 0; //exit(1); } for(int i=0;i<200;i++) { X.bk=infile.get(); line++; if(X.bk=='"')
//////////////////////////////////////////////////////////////////
// 进栈前去掉" " ' '的当作字符的括号首先//想到infile.ignore(n,'/*'),跳过,但无法计R各L,
//用while(){infile.ignore();line++},
//又会在当引号里字符奇偶性会可能// 导致"被跳过,没有终止条件,对奇偶判//断显得复杂了 //用Continue结束实现 while(infile.get()!='"') {
continue;
line++;
}
if(X.bk==39)
// infile.ignore(20,39); while(infile.get()!=39) { continue; line++; }
if(X.bk=='\n')//字符回车时行加1,列归0 { row++; line=0; } if (X.bk==A.bk||X.bk==B.bk||X.bk==C.bk) //读到左括号进栈 { X.row=row; X.line=line; istack.push(X); } //cout<<istack.size()<<endl; if(X.bk==a.bk||X.bk==b.bk||X.bk==c.bk) //读到右括号出栈 { if(istack.size()==0) //栈为空时当前括号出错 { cout<<X.bk<<" 坐标:"<<"x"<<row<<",y"<<line<<endl; dis=3; } else { X.row=row; X.line=line;
dis=fabs(X.bk-istack.top().bk);//
//当括号能匹配时出栈'('=40, ')'=42,'['=91,']'=93,'{'=123,'}'=125利用这个关系 if(dis<=2) // { // istack.pop(); //匹配时出栈 } // else { cout<<istack.top().bk<<" 坐标:"<<"x"<<istack.top
().row<<",y"<<istack.top().line<<endl; cout<<X.bk<<" 坐标:"<<"x"<<row<<",y"<<line<<endl; istack.pop(); } }
} } if(dis<=2&&istack.size()==0) { cout<<"It's OK!"<<endl; return 0; } while(istack.size()!=0) { cout<<istack.top().bk<<" 坐标:"<<"x"<<istack.top().row<<",y"<<istack.top
().line<<endl; istack.pop(); }
infile.close(); return 0; } |