//考虑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;
}
}
}
LL(1)文法分析,自上向下
最新推荐文章于 2024-06-10 20:06:32 发布