递归下降程序一般是针对某一个文法的。而递归下降的预测分析是为每一个非终结符号写一个分析过程,由于文法本身是递归的,所以这些过程也是递归的。 以上是前提。
//递归下降分析程序
#include<iostream>
#include<cstdio>
#include<sstream>
#include<cstring>
#include<string>
#include<cstdlib>
using namespace std;
string str;
size_t lookahead = 0;
string alphabet[] = {
"int","float","(",")","id",","
};
//( int | float )id(,id)*
//正规式表达
void D();
void T();
void L();
void R();
void error();
void error() {
cout<<"Syntax Error!"<<endl;
}
void D() {
T();
L();
}
void T() {
string m1 = str.substr(lookahead, 3);
string m2 = str.substr(lookahead, 5);
if (m1 == "int")
{
lookahead += 3;
}
else if (m2 =="float") {
lookahead += 5;
}
else
error();
}
void L() {
string m3 = str.substr(lookahead, 2);
if (m3 == "id") {
lookahead += 2;
R();
}
else
error();
}
void R() {
if (str[lookahead] == ',') {
lookahead += 1;
string m4 = str.substr(lookahead, 2);
if (m4 == "id") {
lookahead += 2;
R();
}
else
error();
}
}
int main(void) {
int n;
cout<<"Test Number:" << endl;
cin >> n;
while (n--)
{
cout << "Input:";
cin >> str;
str.append("$");
str.append("\0");
D();
if (str[lookahead] == '$')
cout << "Accepted" << endl;
else
error();
lookahead= 0;
}
return 0;
}