📄 词法分析.cpp
字号:
#include<iostream.h>
#include<string.h>
#include<stdio.h>
#define LT 12
#define LE 13
#define EQ 14
#define NE 15
#define GT 16
#define GE 17
#define FZ 18
#define DIV 19
#define jing 20
#define semicolon 21
#define leftpar 22
#define rightpar 23
#define ID 24 //标志符
#define INT 25//整数
#define YH 26
struct KeyWord //关键字结构
{
char *word;
int id;
};
KeyWord keyword[]={ //关键字数组
{"int",1},
{"main",2},
{"if",3},
{"for",4},
{"else",5},
{"printf",6},
{"scanf",7},
{"float",8},
{"double",9},
{"stdio.h",10},
{"include",11}
};
char TOKEN[20];
int graphnum=1; //记录错误所在的位置
int lookup(char *string);
void out(int id,char *string);
void report_error(char ERR_CH);
bool isalpha(char c) ;
bool isdigit(char c);
bool isalnum(char c);
void scan(FILE *fp);
int lookup(char *string)
{
for(int i=0;i<sizeof(keyword)/sizeof(KeyWord);i++)
{
if(strcmp(string,keyword[i].word)==0)
return keyword[i].id;
}
return 0;
}
void out(int id,char *string)
{
printf("(%d,%s)\n",id,string);;
}
void report_error(char ERR_CH) //错误处理程序
{
printf("undeclared identifler %c at the %d line!\n",ERR_CH,graphnum);
}
bool isalpha(char c)
{
if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
return true;
else
return false;
}
bool isdigit(char c)
{
if(c>='0'&&c<='9')
return true;
else
return false;
}
bool isalnum(char c)
{
if(isalpha(c)||isdigit(c))
return true;
else
return false;
}
void scan(FILE *fp)
{
char ch;
int i,c;
while(!feof(fp))
{
ch=fgetc(fp);
if(isalpha(ch))
{
TOKEN[0]=ch;
ch=fgetc(fp);
i=1;
while(isalnum(ch))
{
TOKEN[i]=ch;
i++;
ch=fgetc(fp);
}
TOKEN[i]='\0';
fseek(fp,-1,1);
c=lookup(TOKEN);
if(c==0)
out(ID,TOKEN);
else
out(c," ");
}
else if(isdigit(ch))
{
TOKEN[0]=ch;
ch=fgetc(fp);
i=1;
while(isdigit(ch))
{
TOKEN[i]=ch;
i++;
ch=fgetc(fp);
}
TOKEN[i]='\0';
fseek(fp,-1,1);
out(INT,TOKEN);
}
else
switch(ch)
{
case '<': ch=fgetc(fp);
if(ch=='=')
out(LE," ");
else if(ch=='>')
out(NE," ");
else
{
fseek(fp,-1,1);
out(LT," ");
}
break;
case '=':ch=fgetc(fp);
if(ch=='=')
out(EQ," ");
else {fseek(fp,-1,1); out(FZ," ");}
break;
case '>': ch=fgetc(fp);
if(ch=='=')
out(GE," ");
else
{
fseek(fp,-1,1);
out(GT," ");
}
break;
case '/': ch=fgetc(fp); //删除程序中的注释
if(ch=='/')
{
do
{
ch=fgetc(fp);
}while(ch!='\n');
graphnum++;
}
else
{
fseek(fp,-1,1);
out(DIV," ");
}
break;
case '"':out(YH," ");
case '{':out(leftpar," ");break;
case '}':out(rightpar," ");break;
case '(':out(leftpar," ");break;
case ')':out(rightpar," ");break;
case ';':out(semicolon," ");break;
case '#':out(jing," ");break;
case ' ': break; //删除程序中的空格
case '\n': graphnum++; break; //删除程序中的回车,并记录程序编译到第几行
case ' ': break; //删除程序中的横向制表符
case -1: break; //删除文件尾符号
default: report_error(ch);
break;
}
}
return;
}
void main()
{
FILE *fp;
fp=fopen("21.txt","r");
scan(fp);
fclose (fp);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -