状态机简单实现_1

状态机代码备份

第一次参考网上的例子写个状态机

感觉也没什么东西

开始以为多神秘

其实就是,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;


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值