Problem Description
文法G[S]:
S→Ap
S→Bq
A→ a
A→cA
B→ b
B→dB
试编写一个预测分析程序, 判断文法G所能接受的串。
Input 输入多行由终止符构成的符号串,输入EOF结束。
Output 每行输入的符号串在语法结构上如果合法,输出"syntax correct";否则输出"syntax error"。
Sample Input
ccap#
cccccccccccap#
Sample Output
syntax correct syntax
correct
C++代码实现
//
// Created by Visunf Chen on 2020-10-25.
//
#include "iostream"
using namespace std;
string str;
int flag=1;
void S(string s);
void A(string s);
void B(string s);
void S(string string1){
str = string1;
A(str);
if (str[0]=='p')str = str.substr(1,str.length());
B(str);
if (str[0]=='q')str = str.substr(1,str.length());
}
void A(string string1){
str = string1;
if (str[0]=='a')str = str.substr(1,str.length());
else if(str[0]=='c'){
str = str.substr(1,str.length());
A(str);
}
}
void B(string string1){
str = string1;
if (str[0]=='b')str = str.substr(1,str.length());
else if(str[0]=='d'){
str = str.substr(1,str.length());
B(str);
}
}
int main(){
while (cin>>str&&str!="EOF"){
S(str);
if (str[0]=='#'&&flag==1)cout<<"syntax correct"<<endl;
else cout<<"syntax error"<<endl;
}
return 0;
}