D - 表达式语法分析——递归子程序法

include<bits/stdc++.h>

using namespace std;
int num=0; //用于输出时使用
int i=0; //i用于跟踪当前处理的字符位置
string s;//输入的字符串s

void E();
void G();
void T();
void S();
void F();

void E()
{
if(s[i]'('||s[i]'i')// E的产生式只能处理'('或'i'开头的字符串
{
cout<<num++<<" "<<"E-->TG"<<endl;// 输出使用的产生式,num自增
T();
G();
}
else
{
cout<<"error"<<endl;
exit(0);//程序退出操作
/*
return 0:是函数返回语句,仅用于退出当前函数,并将返回值 0 传递给函数的调用者
exit(0):是标准库函数(声明在 中),作用是直接终止整个程序,无论当前处于哪个函数中
*/
}
}

void G()
{
if(s[i]=='+')// 如果当前字符是'+',使用G->+TG产生式
{
i++; // 跳过'+'
cout<<num++<<" "<<"G-->+TG"<<endl;
T();
G();
}
else// 否则使用空产生式G->ε(这里用&表示空)
{
cout<<num++<<" "<<"G-->&"<<endl;
}
}

void T()
{
if(s[i]'('||s[i]'i')
{
cout<<num++<<" "<<"T-->FS"<<endl;
F();
S();
}
else
{
cout<<"error"<<endl;
exit(0);
}
}

void S()
{
if(s[i]=='')
{
i++; //跳过'
'
cout<<num++<<" "<<"S-->*FS"<<endl;
F();
S();
}
else
{
cout<<num++<<" "<<"S-->&"<<endl;
}
}

void F()//特别注意,容易出错
{
if(s[i]'(')
{
i++; //跳过'('
cout<<num++<<" "<<"F-->(E)"<<endl;
E();
if(s[i]
')')//因为前面i++跳过'('了,所以此处无需使用s[i+1]
{
i++;//跳过')'
}
else
{
cout<<"error"<<endl;
exit(0);
}
}
else if(s[i]=='i')
{
i++; //跳过'i'
cout<<num++<<" "<<"F-->i"<<endl;
}
else
{
cout<<"error"<<endl;
exit(0);
}
}

int main()
{
cin>>s;
E();//从开始符E开始进行语法分析
if(s[i]=='#')//结束标志
{
cout<<"accept";
}
else
{
cout<<"error";
}
return 0;
}

posted @ 2025-11-18 08:44  W001hhhFA  阅读(0)  评论(0)    收藏  举报