实验二利用自动机理论实现词法分析器
1.实验目的熟悉词法分析阶段的要求,掌握利用自动机理论实现词法分析器的方法。
2.实验设备硬件:PC 机一台软件:Windows 系统,高级语言集成开发环境
3.实验内容根据词法要求采用自动机理论实现词法分析器
4.实验要求及步骤
- 理解课件第3章26、27张的词法表述和状态图表示;
- 将课件第3章26张的状态图转换为确定有限自动机的状态转换矩阵;
- 根据DFA的状态转换矩阵实现词法分析器;
- 总结对比实验一和实验二。
注:
1、实现语言不限,推荐使用C语言,不可用脚本类语言;
2、不允许使用任何语言的正规式控件实现实验要求。
根据改状态图写代码
#includeusing namespace std; #include static int Array[14][10] = { { 0, 1, 3, 5, 6, 7, 10, 11, 12, 13}, {2, 1, 1, 2, 2, 2, 2, 2, 2, 2}, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 4, 3, 4, 4, 4, 4, 4, 4, 4}, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 8, 8, 8, 8, 9, 8, 8, 8, 8}, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, }; int CheckCode(char ch) { if (ch == ' ') { return 0; } else if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z') { return 1; } else if (ch >= '0' && ch <= '9') { return 2; } else if (ch == '=') { return 3; } else if (ch == '+') { return 4; } else if (ch == '*') { return 5; } else if (ch == ',') { return 6; } else if (ch == '(') { return 7; } else if (ch == ')') { return 8; } else return 9; } int main() { string sr = "int a aaa aaa **** = ,"; string temp = ""; int temp_char; int now = 0; int next_input; cout << sr << endl; for (int i = 0; i < sr.length(); i++) { temp_char = sr[i]; next_input = CheckCode(temp_char); while (1) { int flag = Array[now][next_input]; if (flag == 0) { now = flag; temp_char = sr[++i]; next_input = CheckCode(temp_char); } else if (flag == 1 | flag == 3 | flag == 7) { //非终态根据下个符号来判断 temp += temp_char; now = flag; temp_char = sr[++i]; next_input = CheckCode(temp_char); } else if (flag == 2 | flag == 4 | flag == 8) { //终结符后带*的处理 if (flag == 2) { cout << '<' << temp << ',' << "标识符" << '>' << endl; } else if (flag == 4) { cout << '<' << temp << ',' << "数" << '>' << endl; } else if (flag == 8) { cout << '<' << temp << ',' << "*号终结符" << '>' << endl; } temp = ""; now = 0; break; } else { //终结符后不带*处理 temp += temp_char; if (flag == 5) { cout << '<' << temp << ',' << "=号终结符" << '>' << endl; } else if (flag == 6) { cout << '<' << temp << ',' << "+号终结符" << '>' << endl; } else if (flag == 9) { cout << '<' << temp << ',' << "**号终结符" << '>' << endl; } else if (flag == 10) { cout << '<' << temp << ',' << "逗号终结符" << '>' << endl; } else if (flag == 11) { cout << '<' << temp << ',' << "(号终结符" << '>' << endl; } else if (flag == 12) { cout << '<' << temp << ',' << ")号终结符" << '>' << endl; } else { cout << '<' << temp << ',' << "其他终结符" << '>' << endl; } temp = ""; now = 0; break; } } } }
运行截图:
并无考虑c语言c++保留字,误喷仅仅供个人编译语言考试参考使用
代码中Array 和CheckCore 函数参考学长的,如有侵权联系我删除



