北邮编译原理词法分析文档和程序Word格式文档下载.docx
《北邮编译原理词法分析文档和程序Word格式文档下载.docx》由会员分享,可在线阅读,更多相关《北邮编译原理词法分析文档和程序Word格式文档下载.docx(14页珍藏版)》请在冰豆网上搜索。
1.词法分析程序的功能:
输入源程序,输出单词符号的记号形式,如图所示:
源程序词法分析器单词符号的记号形式
2.处理过程:
每次调用词法分析程序,它均能自动继续扫描下去,形成下一个单词,直至整个源程序全部扫描完毕,并形成相应的单词串形式的源程序。
六.代码
#include<
iostream>
fstream>
string>
#include<
iomanip>
usingnamespacestd;
stringkeyword[32]={"
auto"
"
break"
case"
char"
const"
//关键字
"
continue"
default"
do"
double"
else"
extern"
enum"
float"
for"
goto"
if"
int"
long"
return"
register"
static"
short"
signed"
unsigned"
struct"
switch"
sizeof"
typedef"
union"
volatile"
void"
while"
};
intcolumn=0,row=1,character=0,word=0;
ifstreaminf("
test.txt"
ios:
:
in);
charc;
intfind_key(stringword)//匹配关键字
{
for(inti=0;
i<
32;
i++)
if(keyword[i].compare(word)==0)
return1;
return0;
}
voidchoice()
while(c=='
\n'
||c=='
'
\t'
)//不计空白符
{
if(c=='
)
row++;
column=0;
//row清零,重新计数另一行
c=inf.get();
column++;
return;
voidget()//读取字符
character++;
intprocess()
stringstr="
"
;
if(inf.fail())
cout<
<
请创建test.txt并输入程序"
endl;
else
ofstreamoutf("
out.txt"
);
outf<
setw(10)<
正规表达式"
setw(30)<
记号"
属性"
while(c!
=EOF)
switch(c){//匹配字符对应记号
case'
a'
...'
z'
A'
Z'
_'
word++;
while(isalpha(c)||isdigit(c)||c=='
str+=c;
get();
if(c=='
@'
?
'
$'
#'
inttag=column;
)
str<
ERROR"
错误在第"
row<
行第"
tag<
列"
str="
break;
if(find_key(str))
关键字"
id"
标示符"
0'
9'
while(isdigit(c)||c=='
.'
e'
E'
if(isalpha(c))
while(isalpha(c)||c=='
||isdigit(c)||c=='
num"
无符号数"
case'
>
='
="
relop"
关系运算符"
elseif(c=='
bit_op"
位运算符"
=="
assign_op"
赋值符"
!
logic_op"
逻辑运算符"
|'
||"
|"
&
+'
++"
alg_op"
运算符"
+="
+"
-'
--"
-="
-"
*'
*="
*"
\"
character--;
str+='
literal"
字符串"
/'
/="
c!
annotation"
注释"
}
chartag=c;
while(tag!
=EOF)
tag=c;
choice();
/"
caseEOF:
default:
c<
符号"
语句行数:
单词个数:
word<
字符个数:
character<
inf.close();
outf.close();
intmain()
intflag;
flag=process();
if(flag==1)
词法分析源程序详见test.txt"
词法分析结果及错误分析详见out.txt"
//输出结果
system("
pause"
七.测试数据:
(1)运行程序
(2)测试代码test.txt
(3)输出结果out.txt