Want more features on Pastebin? Sign Up, it's FREE!
Guest

FSM_Basic

By: a guest on Jul 17th, 2011  |  syntax: C++  |  size: 1.13 KB  |  views: 136  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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. }
clone this paste RAW Paste Data