ExpL语言词法分析:
源代码:
#include<iostream>
#include<string> //头文件
using namespace std;
string line[100]; //存储代码
int row; //代码行数
bool digit(char ch) { return (ch >= '0' && ch <= '9') ? 1 : 0; } //判断数字
bool letter(char ch) { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ? 1 : 0; } //判断字母
int main() { //主程序入口
cout << "请输入源程序代码行数:" << endl;
cin >> row;
cout << "请输入源程序代码:" << endl;
for (int i = 0; i <= row; i++) getline(cin, line[i]);
cout << endl;
cout << "Lexical Analysis:" << endl; //开始词法分析
for (int i = 1; i <= row; i++) { //按行遍历
string str = line[i]; //定义str临时存储
for (int j = 0; j < str.size(); j++) { //遍历str
char ch=str[j]; //准备判断第一个字符
if (letter(ch)) { //是字母
int flag = j, k; string all = ""; all += ch;
for (k = flag + 1; k < str.size(); k++) { //for循环遍历
if (!(digit(str[k]) || letter(str[k]))) break; //第一个是字母,后面可以是数字也可以是字母
all += str[k];
}
j = k - 1; //更新j值
if (all == "output") cout << "(output, )" << endl; //注意output是关键字
else cout << "(ID," << all << ")" << endl; //输出标识符
}
else if (digit(ch)) { //是数字
int flag = j, k; string all = ""; all += ch;
for (k = flag + 1; k < str.size(); k++) { //for循环遍历
if (!(digit(str[k]) || str[k] == '.')) break; //第一个是数字,后面可以是数字也可以是小数点
all += str[k];
}
j = k - 1; //更新j值
cout << "(NUM," << all << ")" << endl; //输出数字
}
else if (ch == ';' || ch == '=' || ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '(' || ch == ')') {
cout << "(" << ch << ", )" << endl; //若是符号直接输出
}
}
}
return 0; //返回值
}
测试样例: