基于C++DFA编程的实现

实验一识别器实现(4学时)

已知DFA如下:

image

请编程输出符号串aacd# 识别过程,如下表所示:

image

二、源程序及运行结果截图

A b c d

1 3 2

2 4

3 3 4 2

4

运行截图:
image

代码实现:

#include<iostream>
#include<string>
#include<windows.h>

using namespace std;


void gotoxy(int x, int y)
{
	CONSOLE_SCREEN_BUFFER_INFO    csbiInfo;
	HANDLE    hConsoleOut;
	hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
	GetConsoleScreenBufferInfo(hConsoleOut, &csbiInfo);
	csbiInfo.dwCursorPosition.X = x;
	csbiInfo.dwCursorPosition.Y = y;
	SetConsoleCursorPosition(hConsoleOut, csbiInfo.dwCursorPosition);
}

class DFA {
private:
	int  array[10][10] = { {1, 0}, {3, 2}, {4, 3}, {3, 2, 4} };
	int state = 1;
	int start = 1;
	int end = 3;
	int count = 1;
	int i = 0;
	string s;

public:
DFA(string s) {
	this->s = s;
	handle();
}


int move(char ch) {

	string s2(s, count++);

	if ((state == 4&&ch!='#')) {
		cout << "不接受" << endl;
		exit(0);
	}else if(ch == '#') {

		gotoxy(4, count + 1);
		cout << this->state;
		gotoxy(11, count + 1);
		cout << ch;
		gotoxy(22, count + 1);
		cout << "ok    接受" << endl;
		return 1;
}


	if (ch == 'a') {

		gotoxy(4, count + 1);
		cout << this->state;
		gotoxy(11, count + 1);
		cout << ch;
		gotoxy(15, count + 1);
		cout << s2;
		state = array[state][0];

		gotoxy(22, count + 1);
		cout << state << endl;

		return 0;
	}else if (ch == 'b' && state == 3) 
	{
		gotoxy(4, count + 1);
		cout << this->state;
		gotoxy(11, count + 1);
		cout << ch;
		gotoxy(15, count + 1);
		cout << s2;
		state = array[state][2];
		gotoxy(22, count + 1);
		cout << state << endl;

		return 0;
		}else if (ch == 'b' && state == 1) 
		{

			gotoxy(4, count + 1);
			cout << this->state;
			gotoxy(11, count + 1);
			cout << ch;
			state = array[state][1];
			gotoxy(15, count + 1);
			cout << s2;
			gotoxy(22, count + 1);
			cout << state << endl;
			return 0;
		}else if (ch == 'c') {
			gotoxy(4, count + 1);
			cout << this->state;
			gotoxy(11, count + 1);
			cout << ch;
			gotoxy(15, count + 1);
			cout << s2;
			state = array[state][1];
			gotoxy(22, count + 1);
			cout << state << endl;
			return 0;
		}else if (ch == 'd') {
			gotoxy(4, count + 1);
			cout << this->state;
			gotoxy(11, count + 1);
			cout << ch;
			gotoxy(15, count + 1);
			cout << s2;
			state = array[state][0];
			gotoxy(22, count + 1);
			cout << state << endl;
			return 0;
		}
		else {
			cout << "不接受" << endl;
			exit(0);
		}
		
		return 0;
	}

	void handle() {
		state = start;
		for (int i = 0; i < s.length(); i++) {
			move(s.at(i));
		}
	}
};

int main() {
	string input;
	cout << "请输入一个字符串:" << endl;
	cin >> input;
	cout << "| state | ch | 剩余 | 变换 | 备注 |" << endl;
	DFA dfa(input);

	return 0;
}
posted @ 2021-05-12 16:25  乐茶茶  阅读(402)  评论(0编辑  收藏  举报