📄 词法分析器.cpp
字号:
#include "stdafx.h"
#include "stdio.h"
#include "iostream.h"
#include "ctype.h"
#include "string.h"
typedef struct
{
int num;
char word[20];
}key;
int line=1,row=0,r;
key keyword[15]=
{
{1,"PROGRAM"},{2,"CONST"},{3,"VAR"},
{4,"INTEGER"},{5,"LONG"},{6,"PROCEDURE"},
{7,"IF"},{8,"THEN"},{9,"WHILE"},
{10,"DO"},{11,"READ"},{12,"WRITE"},
{13,"BEGIN"},{14,"END"},{15,"ODD"}
};
void output(int m,char * s)
{
cout<<"["<<m<<","<<s<<"]"<<' '<<line<<' '<<row-strlen(s)+1<<endl;
}
char getch(FILE * fp)
{
char ch;
ch=fgetc(fp);
if(ch=='\n')
{
line=line+1;
row=0;
}
else
{
row=row+1;
r=row;
}
return ch;
}
void seek(FILE *fp,char ch)
{
if(ch=='\n')
{
line=line-1;
row=r;
}
else
{
row=row-1;
r=row;
}
fseek(fp,-1,1);
}
int compare(char *s1)
{
int i;
for(i=0;i<20;i++)
{
if(strcmp(s1,keyword[i].word)==0)
return keyword[i].num;
}
return -1;
}
void getsym(FILE * fp)
{
char ch;
int n,m;
char str[20];
int val;
ch=getch(fp);
while(ch==' ')ch=getch(fp);
if(isalpha(ch))
{
n=0;
while(isalnum(ch))
{
if(n<20)
{
str[n]=ch;
n=n+1;
}
ch=getch(fp);
}
seek(fp,ch);
str[n]='\0';
m=compare(str);
if(m!=-1)
output(m,keyword[m-1].word);
else
output(34,str);
}
else if(isdigit(ch))
{
val=0;
int i=0;
while(isdigit(ch))
{
val=val*10+ch-'0';
ch=getch(fp);
i=i+1;
}
seek(fp,ch);
cout<<'['<<33<<','<<val<<']'<<line<<' '<<row-i+1<<endl;
}
else
switch(ch)
{
case '+':output(16,"+");break;
case '-':output(17,"-");break;
case '*':output(18,"*");break;
case '/':output(19,"/");break;
case '=':output(20,"=");break;
case ',':output(26,",");break;
case '.':output(27,".");break;
case ';':output(28,";");break;
case '(':output(31,"(");break;
case ')':output(32,")");break;
case '#':output(35,"#");break;
case '<':
str[0]=ch;
ch=getch(fp);
if(ch=='>')
{
str[1]=ch;
str[2]='\0';
output(21,str);
}
else
{
if(ch=='=')
{
str[1]=ch;
str[2]='\0';
output(23,str);
}
else
{
str[1]='\0';
seek(fp,ch);
output(22,str);
}
}
break;
case '>':
str[0]=ch;
ch=getch(fp);
if(ch=='=')
{
str[1]=ch;
str[2]='\0';
output(25,str);
}
else
{
str[1]='\0';
seek(fp,ch);
output(24,str);
}
break;
case ':':
str[0]=ch;
ch=getch(fp);
if(ch=='=')
{
str[1]=ch;
str[2]='\0';
output(30,str);
}
else
{
str[1]='\0';
seek(fp,ch);
output(29,str);
}
break;
default:
{
if(ch!=EOF&&ch!=' '&&ch!='\n')
cout<<"ERROR: "<<ch<<" line: "<<line<<" row: "<<row<<endl;
}
}
}
int main()
{
FILE *fp;
char wenjian[30];
cout<<"Please input the file you want to transform:";
cin>>wenjian;
fp=fopen(wenjian,"r");
while(!feof(fp))
{
getsym(fp);
}
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -