ステートマシンの簡単な実装_1

1679 ワード

ステートマシンコードバックアップ
初めてネット上の例を参考にステータスマシンを書きます
何も感じない
神秘的だと思った
実はswitch-case文
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;


typedef enum{
	state0 = 0,
	state1 ,
	state2 ,
	state3 ,
	state4 ,


}state;


typedef enum
{
	input1 = '2',
	input2 = '4',
	input3 = '7',
	input4 = '9',
}input;


int main(int argc, char**argv)
{
	char ch = '\0';
	state current_state = state0;
	while (1)
	{
		printf(" 
"); while ((ch = getchar()) != '
') { if((ch > '9') || (ch < '0')) { printf(" !
"); break; } switch (current_state) { case state0://state 1 { if ('2' == ch) { current_state = state1; cout << "state1" << endl; } break; } case state1://state 2 { if ('4' == ch) { current_state = state2; cout << "state2" << endl; } break; } case state2://state 3 { if('7' == ch) { current_state = state3; cout << "state3" << endl; } break; } case state3://state 4 { if('9' == ch) { current_state = state4; cout << "state4" << endl; } break; } default: { current_state = state0; break; } } } if(current_state == state4) { printf("lock is open!
"); break; } else { printf("lock unlocked!
"); } } getchar(); return 0; }