状态机代码备份
第一次参考网上的例子写个状态机
感觉也没什么东西
开始以为多神秘
其实就是,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("输入数字进行解锁\n");
while ((ch = getchar()) != '\n')
{
if((ch > '9') || (ch < '0'))
{
printf("非数字!\n");
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!\n");
break;
}
else
{
printf("lock unlocked!\n");
}
}
getchar();
return 0;
}