词法分析程序(Lexical Analyzer)要求:
- 从左至右扫描构成源程序的字符流
- 识别出有词法意义的单词(Lexemes)
- 返回单词记录(单词类别,单词本身)
- 滤掉空格
- 跳过注释
- 发现词法错误
程序结构:
输入:字符流(创建测试数据a.txt,利用函数freopen()函数读取文件获取数据)
处理:
–遍历(利用do-while循环,通过cin.get()函数逐一获取字符到数组test中)
–词法规则
输出:单词流(判断完标识符的语种后,输出该种别码和该标识符)
–二元组
单词类别:
1.标识符(10)
2.无符号数(11)
3.保留字(一词一码)
4.运算符(一词一码)
5.界符(一词一码)
具体表格如下:
单词符号 |
种别码 |
单词符号 |
种别码 |
begin |
1 |
<= |
21 |
if |
2 |
<> |
22 |
then |
3 |
> |
23 |
while |
4 |
>= |
24 |
do |
5 |
= |
25 |
end |
6 |
== |
26 |
l(l|d)* |
10 |
! |
27 |
dd* |
11 |
!= |
28 |
+ |
13 |
; |
29 |
- |
14 |
( |
30 |
* |
15 |
) |
31 |
/ |
16 |
[ |
32 |
: |
17 |
] |
33 |
:= |
18 |
{ |
34 |
< |
20 |
} |
35 |
# |
0 |
$ |
-1 |
程序代码如下:
1 #include<stdio.h> 2 #include<string.h> 3 #include<iostream> 4 using namespace std; 5 6 int row=1;//记录行 7 int p=0; 8 int m=0; 9 char ans; 10 char test[200];//存放输入 11 char word[200];//存放经过转化的 12 const char *keyword[]={"begin","if","then","while","do","end"};//保留字 13 const char *symbol[]={"+","-","*","/",":",":=","<","<=","<>",">",">=","=",";","(",")","==","!","!=","/*","*/","[","]","{","}"}; 15 char comments[200]; 16 int mark=0;//用来记录输出的种别码 17 long long int sum=0;//记录和 18 19 void transfer(){//扫描字符串 20 int i,j; 21 for(j=0;j<200;j++) //每一次都要重新赋值 22 word[j]='