📄 词法分析施.cpp
字号:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define ID 6 //标识符
#define INT 7 //整数
#define LT 8 //小于
#define LE 9 //小于等于
#define EQ 10 //等于
#define NE 11 //不等于
#define GT 12 //大于
#define GE 13 //大于等于
#define ADD 14 //加"+"
#define SUB 15 //减"-"
#define MUL 16 //乘"*"
#define DIV 17 //除"/"
#define FH 18 //分号;
#define DH 19 //逗号,
#define ZHK 20 //左花括{
#define YHK 21 //右花括}
#define ZK 22 //左括(
#define YK 23 //右括)
char ch;
FILE *fp1,*fp2;
void get() //检查ch是否为空白符,是的话,继续取下一个字符,直到不为空
{
while(ch==32||ch==10) ch=fgetc(fp1);
}
int isalpha() //判断ch是否为字母
{
if((ch>='A')&&(ch<='Z')||(ch>='a')&&(ch<='z')) return 1;
else return 0;
}
int isalnum() //判断ch是否为数字
{
if(ch>='0'&&ch<='9') return 1;
else return 0;
}
void report_error(char *ch)//报错
{
fp2=fopen("out.txt","a");
fseek(fp2,44L,0);
fprintf(fp2,"<%s , error!>\n",ch);
fclose(fp2);
cout<<ch<<" error!"<<endl;
}
void out(int x,char *ch) //输出函数,以二元组的形式从文件中输出
{
cout<<x<<" "<<ch<<endl;
fp2=fopen("out.txt","a");
fseek(fp2,44L,0);
fprintf(fp2,"<%d , %s>\n",x,ch);
fclose(fp2);
}
int lookup(char *TOKEN) //判断TOKEN中的字符是否为关键字
{
int key=0,i;
char key_word[6][6]={"main","if","else","int","while","char"};
for(i=0;i<6;i++)
if(strcmp(TOKEN,key_word[i])==0) {key=i+1; break;}
return key;
}
void scanner_example() //扫描函数
{
int i=0,c;
char TOKEN[20];
ch=fgetc(fp1);
get();
if(isalpha())//字母
{
TOKEN[0]=ch;
ch=fgetc(fp1);
i=1;
while(isalpha())//指针右移查找下一个
{
TOKEN[i]=ch;
ch=fgetc(fp1);
i++;
}
TOKEN[i]='\0';
fseek(fp1,-1L,1);//指针回返一个
c=lookup(TOKEN);
if(c==0) out (ID,TOKEN);//标识符
else out(c,TOKEN);//单词
}
else
if(isalnum())//数字
{
TOKEN[0]=ch;
ch=fgetc(fp1);
i=1;
while(isalnum())//指针右移查找下一个
{
TOKEN[i]=ch;
ch=fgetc(fp1);
i++;
}
fseek(fp1,-1L,1);
TOKEN[i]='\0';
out(INT,TOKEN);//整数
}
else
switch(ch)//其他符号
{
case '<':ch=fgetc(fp1);
if(ch=='=') out(LE,"<=");//小于等于
else if(ch=='>') out(NE,"<>");//不等于
else
{
fseek(fp1,-1L,1);//指针回退一位
out(LT,"<");//小于
}
break;
case '=':out(EQ,"=");break;
case '>':ch=fgetc(fp1);
if(ch=='=') out(GE,">=");//大于等于
else
{
fseek(fp1,-1L,1);//指针回退一位
out(GT,">");//大于
}
break;
case '+':out(ADD,"+");break;
case '-':out(SUB,"-");break;
case '*':out(MUL,"*");break;
case '/':out(DIV,"/");break;
case ';':out(FH,";"); break;
case ',':out(DH,","); break;
case '{':out(ZHK,"{");break;
case '}':out(YHK,"}");break;
case '(':out(ZK,"("); break;
case ')':out(YK,")"); break;
default:{TOKEN[0]=ch;TOKEN[1]='\0';report_error(TOKEN);break;}
}
}
void main()
{
char filename[20];
printf("\n请输入文件(注意文件路径及类型<.cpp>哦) :");/*输入要编译文件的名字和路径*/
scanf("%s",filename);
if((fp1=fopen(filename,"r"))==NULL) printf("您输入的文件名找不到!\n");
fp2=fopen("out.txt","w");
fclose(fp2);
while(ch!=EOF)
{
scanner_example();
}
fclose(fp1);
getch();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -