LL(1)文法分析,自上向下

//考虑LL(1)递归方式解决

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

//声明变量,用来只是字符串内的指针
int indexString = 0;

//判断表达式中括号对是否匹配
bool flag = true;

//输入表达式的字符串
string str;

/*///
		对以下文法进行分析
		1:E->TX				4:Y->*FY
		2:X->+TX			5:F->(E)
		3:T->FY				6:F->id
		
///*/
//因为是递归解决,所以先声明函数
void E();
void T();
void X();
void Y();
void F();

int main(int argc, char argv[])
{
	cout << "输入字符串:" << endl;
	cin >> str;
	E();
	if (flag == false)
	{
		cout << "括号不匹配" << endl;
	}
	return 0;
}

void E()
{
	cout << "E->TX" << endl;
	T();
	X();
}
void T()
{
	cout << "T->FY" << endl;
	F();
	Y();
}
void X()
{
	if (str[indexString] == '+')
	{
		indexString++;
		cout << "X->+TX" << endl;
		if(str[indexString]=='*'||str[indexString]=='+')
		{
			cout<<"运算符多余"<<endl;
			indexString++;
		}
		T();
		X();
		if (str[indexString] == ')')
		{
			indexString++;
			flag = true;
		}
	}
}
void Y()
{
	if (str[indexString] == '*')
	{
		indexString++;
		if(str[indexString]=='*'||str[indexString]=='+')
		{
			cout<<"运算符多余"<<endl;
			indexString++;
		}
		cout << "Y->FY" << endl;
		F();
		Y();
	}
}
void F()
{
	if (str[indexString] == '(')
	{
		flag = false;
		cout << "F->(E)" << endl;
		indexString++;
		E();
		if (str[indexString] == ')')
		{
			indexString++;
			flag = true;
		}
	}
	if (str[indexString] == 'i')
	{
		cout << "F->id" << endl;
		indexString += 2;
		if (str[indexString] == ')')
		{
			indexString++;
			flag = true;
		}
		if(str[indexString]=='i')
		{
			cout<<"多一个id"<<endl;
			indexString += 2;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值