/* ECP: FILEname=fig14_26.cpp */ /* 1*/ int /* 2*/ CheckBalance( const String & FileName ) /* 3*/ { /* 4*/ Stack S; /* 5*/ Symbol Last = { 0, 1 }, Match; /* 6*/ int Errors = 0; /* 7*/ ifstream Ifp( FileName, ios::in ); /* 8*/ while( Ifp.get( Last.Sym ) ) /* 9*/ switch( Last.Sym ) /*10*/ { /*11*/ case '\n': /*12*/ Last.Line++; /*13*/ break; /*14*/ case '(': case '[': case '{': /*15*/ S.Push( Last ); /*16*/ break; /*17*/ case ')': case ']': case '}': /*18*/ if( S.IsEmpty( ) ) /*19*/ { /*20*/ Errors++; /*21*/ cout << "Extraneous " << Last.Sym << /*22*/ " at line " << Last.Line << endl; /*23*/ } /*24*/ else /*25*/ { /*26*/ Match = S.Pop( ); /*27*/ if( CheckMatch( Match, Last ) ) /*28*/ Errors++; /*29*/ } /*30*/ break; /*31*/ default: /*32*/ break; /*33*/ } /*34*/ while( !S.IsEmpty( ) ) // Unmatched symbols. /*35*/ { /*36*/ Errors++; /*37*/ Match = S.Pop( ); /*38*/ cout << "Unmatched " << Match.Sym << " at line " /*39*/ << Match.Line << endl; /*40*/ } /*41*/ return Errors; /*42*/ }