Advertisement
Guest User

FSM_Basic

a guest
Jul 17th, 2011
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. enum states { before = 0, inside = 1, after = 2 };
  4.  
  5. class StateMachine
  6. {
  7.   private:
  8.     enum states state;                                      // Current state
  9.     struct branch
  10.     {
  11.         enum states new_state:2;
  12.         int should_putchar:1;
  13.     };
  14.     static struct branch transition_table[3][3];           // Transition map
  15.  
  16. public:
  17.     StateMachine() : state(before) {}                      // Constructor with starting state
  18.     void process_event(int c)
  19.     {
  20.         int idx2 = (c == ' ') ? 0 : (c == '\n') ? 1 : 2;
  21.         struct branch *b = & transition_table[state][idx2];
  22.         state = b->new_state;
  23.         if(b->should_putchar) putchar(c);
  24.     }
  25. };
  26.  
  27. struct StateMachine::branch StateMachine::transition_table[3][3] =
  28. {
  29.                  /* ' '         '\n'        others */
  30.     /* before */ { {before,0}, {before,1}, {inside,1} },
  31.     /* inside */ { {after, 0}, {before,1}, {inside,1} },
  32.     /* after  */ { {after, 0}, {before,1}, {after, 0} }
  33. };
  34.  
  35. int main(void)
  36. {
  37.     int c;
  38.     StateMachine FSM;
  39.     while((c = getchar()) != EOF)
  40.         FSM.process_event(c);
  41.     return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement