词法分析程序(Lexical Analyzer)要求:
- 从左至右扫描构成源程序的字符流
- 识别出有词法意义的单词(Lexemes)
- 返回单词记录(单词类别,单词本身)
- 滤掉空格
- 跳过注释
- 发现词法错误
程序结构:
输入:字符流(什么输入方式,什么数据结构保存)
处理:
–遍历(什么遍历方式)
–词法规则
输出:单词流(什么输出形式)
–二元组
源程序如下:
1 #include<stdio.h> 2 #include<conio.h> 3 #include<math.h> 4 #include<string.h> 5 #include<stdlib.h> 6 7 int i, row = 0, line = 0; 8 char test[1000]; //test文件中的字符 9 int number[100]; //常数表 10 char mark[100][5]; //标识符表 11 12 //词法分析 13 int wordanalysis() 14 { 15 //标识符和保留字 16 if ((test[i] >= 'A'&&test[i] <= 'Z')||(test[i]>='a'&&test[i]<='z')) 17 { 18 char word[10]; 19 //保留字表 20 char pro[100][100] = { "PROGRAM", "BEGIN", "END", "VAR", "INTEGER", "WHILE", 21 "IF", "THEN", "ELSE", "DO", "PROCEDURE" ,"char", 22 "int","if","else","var" ,"return","break", 23 "do","while","for","double","float","short"}; 24 25 int n = 0; 26 word[n++] = test[i++]; 27 while ((test[i] >= 'A'&&test[i] <= 'Z') || (test[i] >= '0' && test[i] <= '9')||(test[i]>='a'&&test[i]<='z')) 28 { 29 word[n++] = test[i++]; 30 } 31 word[n] = '