词法分析器-计算器-设计与实现实验报告Word文档格式.docx
《词法分析器-计算器-设计与实现实验报告Word文档格式.docx》由会员分享,可在线阅读,更多相关《词法分析器-计算器-设计与实现实验报告Word文档格式.docx(21页珍藏版)》请在冰豆网上搜索。
数字
非数字
3 4
运算符
5
界符
6
其他
7
空白
词法分析程序:
#include<
stdio.h>
#include<
stdlib.h>
string>
iostream>
usingnamespacestd;
string
keywords[20]={"
include"
"
void"
main"
int"
char"
float"
double"
if"
else"
then
"
break"
continue"
for"
do"
while"
printf"
scanf"
begin"
end"
return"
};
charrz[99999]="
"
;
stringid[10000];
intpp=0;
stringnu[10000];
intqq=0;
intchoice1(chara) //判断是否是字母
{
if((a>
='
a'
&
a<
z'
)||(a>
A'
Z'
))return1;
elsereturn0;
}
intchoice2(chara) //判断是否是数字
if(a>
0'
9'
)
return1;
intalpha(intst) //识别保留字和标识符
charwordbuf[20]="
intn=0;
for(;
;
)
wordbuf[n]=rz[st];
st++;
n++;
if((choice2(rz[st])==1)||(choice1(rz[st])==1)||(rz[st]=='
_'
))wordbuf[n]=rz[st];
elsebreak;
intflag=0;
for(intk=0;
k<
20;
k++)
if(strcmp(keywords[k].c_str(),wordbuf)==0)flag=1;
if(flag==0)
intflagg=-1;
for(intt=0;
t<
pp;
t++)
if(strcmp(id[t].c_str(),wordbuf)==0)
flagg=t;
if(flagg!
=-1)printf("
(id,%d)"
flagg);
else
id[pp]=wordbuf;
printf("
pp);
pp++;
else
printf("
("
);
for(inti=0;
i<
n;
i++)
%c"
wordbuf[i]);
-)"
returnst;
intnumber(intst) //识别整数
charnumbuf[20]="
intk=0;
intflag=0;
for(;
numbuf[n]=rz[st];
if(choice2(rz[st])==1)
elseif((k==0)&
(rz[st]=='
.'
))
k++;
elseif(choice1(rz[st])==1)
flag=1;
continue;
qq;
t++)if(strcmp(nu[t].c_str(),numbuf)==0)flagg=t;
(nu,%d)"
nu[qq]=numbuf;
qq);
qq++;
i++)printf("
numbuf[i]);
errordigital!
) "
intanotation(intst) //处理除号/和注释
chartabuf[9999]="
st++;
if(rz[st]=='
/'
(//,-)"
while(rz[st]!
=10)
tabuf[n]=rz[st];
\n注释"
for(inti=0;
tabuf[i]);
elseif(rz[st]=='
*'
(/*,-) "
intstt=st+1;
while
(1)
rz[st+1]=='
)break;
tabuf[n]=rz[st];
n++;
if(rz[st+1]=='
\0'
(/*error!
!
\n)"
returnst+1;
} printf("
(*/,-) "
st=st+2;
(/*,-)
elseprintf("
(/,-)
intother(intst) //函数识别其他特殊字符
switch(rz[st])
case'
:
(rlop,==) "
(rlop,=) "
break;
+'
(+=,-) "
(++,-) "
(+,-) "
-'
(-=,-) "
(--,-) "
(-,-) "
break;
(*=,-) "
(*,-) "
>
'
(rlop,>
=) "
<
(rlop,<
%'
(\%=,-) "
(\%,-) "
(!
=,-) "
wrongthing!
(&
-) "
worngword!
|'
(||,-) "
(|,worngword!
{'
({,-) "
case'
}'
(},-) "
('
((,-) "
)'
(),-) "
['
([,-) "
]'
(],-) "
(:
#'
(#,-) "
(;
(.,-) "
'
(,,-) "
'
'
case10:
st++;
\n"
case34:
(\"
case39:
('
default:
(%c,wo