设有文法GAA→iBeB→SBS→eCiC→eCe编写一个递归下降分析程序对给定的单词序列判断其是否符合该文法的要求?如果是输出Success否则输出Error。输入格式:一个字符串为单词序列每个符号为一个单词输出格式:Success或者Error。使用C++进行代码的编写
#include
string str; // 全局变量,存储输入的单词序列 int index; // 全局变量,当前处理的单词在序列中的下标
void A(); // 声明 A 函数 void B(); // 声明 B 函数 void S(); // 声明 S 函数 void C(); // 声明 C 函数
void match(char c) { // 匹配函数,判断当前单词是否为 c,是则向后移动一个单词 if (str[index] == c) { index++; } else { cout << "Error" << endl; exit(0); } }
void A() { match('i'); B(); match('*'); match('e'); }
void B() { if (str[index] == 'S') { S(); B(); } }
void S() { if (str[index] == '[') { match('['); match('e'); C(); match(']'); } else if (str[index] == '.') { match('.'); match('i'); } else { cout << "Error" << endl; exit(0); } }
void C() { if (str[index] == 'e') { match('e'); C(); } }
int main() { cin >> str; index = 0; A(); if (index == str.length()) { cout << "Success" << endl; } else { cout << "Error" << endl; } return 0;
原文地址: https://www.cveoy.top/t/topic/hmYC 著作权归作者所有。请勿转载和采集!