1. Use Case Finite State Machine
// Use the password lock based on the state machine (FSM) implemented by switch/case or if/else. // unlock only when the password 2479 is entered correctly # include <stdio. h> # include <stdlib. h> # include <string. h> typedef Enum {state0 = 0, state1, state2, state3, State4,} state; int main () {char ch; State current_state = state0; while (1) {printf ("in put password:"); While (CH = getchar ())! = '\ N') {If (CH <'0') | (CH> '9') {printf ("input num, OK? /N "); break;} switch (current_state) {Case state0: If (CH = '2') current_state = state1; break; Case state1: if (CH = '4') current_state = state2; break; Case state2: If (CH = '7') current_state = state3; break; Case state3: if (CH = '9') current_state = State4; break; default: current_state = state0; break ;}// end inner while if (current_state = State4) {printf ("correct, lock is open! \ N "); current_state = state0;} else {printf (" wrong, locked! \ N "); current_state = state0;} break;} return 0;} // code from http://blog.csdn.net/qp120291570/article/details/8634582
2. Application of finite state machines using function pointers
// A password lock based on the state machine (FSM) implemented by using the function pointer // The password can be unlocked only when 2479 is entered correctly # include <stdio. h> // The password for this secret lock is xxxx2479, that is, the last four digits are 2479, and the first digit is 0 ~ No # include <stdlib. h> # include <string. h> // define the function pointer type of the lock event processing function typedef void (* lock_func_temp) (char C); typedef lock_func_temp (* lock_func) (char C); lock_func state; // The function declares the queue // columns, so that the error lock_func init_state (char ch); lock_func state1 (char ch); lock_func state2 (char ch) will not be reported after cross-reference ); lock_func state3 (char ch); lock_func State4 (char ch); // initial state lock_func init_state (char ch) {If (CH <'0 ') | (CH> '9') Return NULL; else return state1 (CH); // a parameter is required here; otherwise, a character is missing.} // status 1 lock_func state1 (char ch) {If (CH = '2') {return state2;} else {return init_state ;}// status 2 lock_func state2 (char ch) {If (CH = '4') {return state3;} else {return init_state ;}// status 3 lock_func state3 (char ch) {If (CH = '7') {return State4;} else {return init_state ;}// status 4 lock_func State4 (char ch) {If (CH = '9') {printf ("correct, lock is open! \ N "); return NULL;} else {return init_state;} // the end state expressed by return null. // status conversion here void lock_handle (void) {char ch; State = init_state; while (state) {CH = getchar (); State = (* State) (CH) ;}} int main () {lock_handle ();}
3. FSM Application Based on State Matrix
Reference: http://www.cookiebear.info/archives/557