编译原理--基础词法分析实验

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;   //返回值
}

测试样例:

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值