Exercise 3.18 Write a program for detecting balanced symbols in the following languages
A.pascal (Begin/end, (), [], {}).
B.C Language (/* */, (), [], {}).
C. Explaining how to print error messages
Answer:
The essence of A and B is the same, the B is written a small problem that C language detection.
The basic idea is to use the stack, in addition to the comment symbol is a little trouble to see two consecutive characters, the other groups are very relaxed and happy.
The details are put in the notes, so there's no need to say too much in the article.
The test code is not put, basically is to take a text file to change, in the Mian function inside the three lines, in short, the actual measurement is able to pass.
1 //Exercise 3.18 New, check the language balance symbol2 voidChecklang (Ifstream &ifile)3 {4 if(ifile)5 {6stack<Char>check;7 //avoid empty stacks causing getfirst () to throw exceptions8Check.push ('!');9 //string Testall ("() []{}*/");Ten stringPushin ("([{*"); One stringPopout (")]}/"); A CharPrev =' /'; - CharCurr; -IFile >>Curr; the while(!ifile.eof ()) - { - //if the top of the stack is an annotation, all skips unless a counter-comment is present - if(Check.getfirst () = ='/') + { - if(prev = ='*'&& Curr = ='/') + Check.pop (); A } at Else - { - //If the start flag is detected - if(Pushin.find (curr)! =string:: NPOs) - { - //directly into the stack if it is a single-match character in if(Curr! ='*') - Check.push (curr); to //If the comment is in the stack + Else if(prev = ='/') -Check.push ('/'); the //Otherwise, there must be curr = = ' * ', while prev! = '/', do not proceed with the Operation * } $ //If the end flag is detectedPanax Notoginseng Else if(Popout.find (curr)! =string:: NPOs) - { the //if it is a three single symbol + //the corresponding pop-up can not be corresponding to jump out and will error A if(Curr = =')') the { + if(Check.getfirst () = ='(') - Check.pop (); $ Else $ Break; - } - Else if(Curr = =']') the { - if(Check.getfirst () = ='[')Wuyi Check.pop (); the Else - Break; Wu } - Else if(Curr = ='}') About { $ if(Check.getfirst () = ='{') - Check.pop (); - Else - Break; A } + //if it's a counter-comment the Else if(prev = ='*') - { $ if(Check.getfirst () = ='/') the Check.pop (); the Else the Break; the } - //No action if not anti-comment in } the } the //Read Next character AboutPrev =Curr; theIFile >>Curr; the } the //if Curr does not reach the end of the file + //is bound to jump out of the loop because of the wrong single-symbol correspondence - if(!ifile.eof ()) the {Bayicout << Curr <<" and"<< Check.getfirst () <<Endl; thecout <<"Incorrect pop!"<<Endl; the } - //If the end of the file is reached, the top of the stack is not the initial '! ' - //must have the second half balance missing the Else if(Check.getfirst ()! ='!') thecout <<"Missing ending!"<<Endl; the Else thecout <<"Success"<<Endl; - check.clear (); the } the Else thecout <<"cannot find stream!"<<Endl;94}
"Weiss", "No. 03 chapter" Exercise 3.18