/* * Nancy Ide * Character Stream Reader * Sample solution for CS331 * */ #include "char_stream.h" #include "error.h" #include extern char Current_Line[]; // current input line extern int Line_Number; // line counter CharStream::CharStream() { fOpened = false; } CharStream::CharStream(const char filename[]) { this->open(filename); fOpened = this->good(); Line_Number = 0; if (fOpened) SkipWhite(); } void CharStream::Push_back(char Look_Ahead) { CharStack.push(Look_Ahead); } void CharStream::SkipWhite(void) { if ( Current_Line[Current_Char] == L_CURLY ) SkipComment(); while ( Current_Line[Current_Char] == BLANK || Current_Line[Current_Char] == TAB) { Advance(); if ( Current_Line[Current_Char] == L_CURLY ) SkipComment(); } } void CharStream::SkipComment(void) { while ( Current_Line[Current_Char] != R_CURLY ) { Advance(); if ( Current_Line[Current_Char] == L_CURLY ) throw Error(1); } Advance(); } CharStream::~CharStream() { if ( fOpened ) this->close(); } char CharStream::CurrentChar(void) { char C; if ( !CharStack.empty() ) { C = ( CharStack.top() ); CharStack.pop(); return( C ); } C = ( Current_Line[Current_Char] ); if ( C == EOL_CHAR ) { GetNewLine(); while ( Current_Line[Current_Char] == EOL_CHAR ) // handle multiple blank lines GetNewLine(); return(BLANK); } if ( C == L_CURLY ) { SkipComment(); return(BLANK); } if ( C == BLANK || C == TAB ) // First blank is returned as a delimeter { SkipWhite(); return(BLANK); } Advance(); return (C); } void CharStream::GetNewLine(void) { if (eof()) { Current_Char = 0; Current_Line[Current_Char] = EOF_CHAR; } else { getline(Current_Line,LINE_SIZE-1); ++Line_Number; Current_Char = 0; SkipWhite(); } } void CharStream::Advance(void) { if ( Current_Line[Current_Char] == EOL_CHAR ) GetNewLine(); else ++Current_Char; } bool CharStream::Open(const char filename[]) { this->open(filename); fOpened = this->good(); return fOpened; } void CharStream::Close(void) { if ( fOpened ) this->close(); } bool CharStream::Valid (char c) { return( ( c == EOL_CHAR ) || ( strchr( VALID_CHARS,c ) != NULL ) ); }