< previous page page_272 next page >

Page 272
(text box continued from previous page)
   else if (currChar != !)     // Rule: If currChar isn't
                                 //         = or !,
      exclamEncountered = FALSE; //     switch states
}
else                             // State == no ! encountered
   if (currChar == !)          // Rule: If currChar is !,
      exclamEncountered = TRUE;  //       switch states
Next, we wrap these state tests and transition rules in a loop that applies them to each input character. In addition, we must specify a starting state for the finite state machine by initializing all of the state variables. In this case, we just have to set exclamEncountered to FALSE. Here's the new program:
//******************************************************************
// FiniteState program
// This program counts the occurrences of != in a data file
// by simulating a finite state machine
//******************************************************************
#include <iostream.h>
#include <fstream.h>   // For file I/O

typedef int Boolean;
const Boolean TRUE = 1;
const Boolean FALSE = 0;

int main()
{
    int      count;             // Number of != operators
    char     currChar;          // Current character
    Boolean exclamEncountered;  // State variable
    ifstream inFile;            // Data file

    inFile.open(myfile.dat);
    if ( !inFile )
    {
       cout << ** Can't open input file ** << endl;
       return 1;
    }
    count = 0;
    exclamEncountered = FALSE;          // Initialize starting state
    inFile.get(currChar);
    while (inFile)
    {
       if (exclamEncountered)           // State == ! encountered
       {
          if (currChar == =)          // Rule: If currChar is =,
          {
             count++;                   //       increment count
             exclamEncountered = FALSE; //       and switch states
          }

(text box continues on next page)

 
< previous page page_272 next page >