编译原理---表达式语法分析(预测分析法)

题目:

 

#include <iostream>
#include <algorithm>
#include <stack>
#include <string>
using namespace std;

int num;
stack<char> A;
stack<char> B;
int Begin(char x,char y)/*根据预测分析表x代表非终结符号,y代表输入符号*/
{
	if (x == 'E' && (y == 'i' || y == '('))
	{
		cout << num << " " << "E->TG" << endl;
		A.pop();
		A.push('G');
		A.push('T');
		num++;
		return 1;

	}
	else if (x == 'G' && y == '+')
	{
		cout << num << " " << "G->+TG" << endl;
		A.pop();
		A.push('G');
		A.push('T');
		A.push('+');
		num++;
		return 1;
	}
	else if (x == 'G' && (y == ')' || y == '#')) {
		cout << num << " " << "G->^" << endl;
		A.pop();
		num++;
		return 1;
	}
	else if (x == 'T' && (y == 'i' || y == '(')) {
		cout << num << " " << "T->FS" << endl;
		A.pop();
		A.push('S');
		A.push('F');
		num++;
		return 1;
	}
	else if (x == 'S' && y == '*') {
		cout << num << " " << "S->*FS" << endl;
		A.pop();
		A.push('S');
		A.push('F');
		A.push('*');
		num++;
		return 1;
	}
	else if (x == 'S' && (y == '+' || y == ')' || y == '#')) {
		cout << num << " " << "S->^" << endl;
		A.pop();
		num++;
		return 1;
	}
	 else if (x == 'F' && y == 'i') {
		cout << num << " " << "F->i" << endl;
		A.pop();
		A.push('i');
		num++;
		return 1;
	}
	else  if (x == 'F' && y == '(') {
		cout << num << " " << "F->(E)" << endl;
		A.pop();
		A.push(')');
		A.push('E');
		A.push('(');
		num++;
		return 1;
	}
	else{
		if (x == y) {
			A.pop();
			B.pop();
			return 1;
		}
		else
			return 0;
	}
}
void check()
{
	num = 1;
	while (!A.empty()) {
		A.pop();
	}
	A.push('#');
	A.push('E');
	while (!B.empty()) {
		B.pop();
	}

}
int main()
{
	string s;
	while (cin >> s) {
		check();
		int len = s.length();
		for (int i = len - 1; i >= 0; i--) {
			B.push(s[i]);
		}
		while (1) {
			if (A.top() == '#' && B.top() == '#')
			{
				cout << "acc!" << endl;
				break;
			}
			else
			{
				int key = Begin(A.top(), B.top());
				if (key == 0)
				{
					cout << "error!" << endl;
					break;
				}
			}
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值