📄 cifa.cpp
字号:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <ctype.h>
#include <conio.h>
#define NULL 0
FILE *fp;
char ch;
char *keyword[8]={"do","begin","else","end","if","then","var","while"};
char *operatornum[4]={"+","-","*","/"};
char *comparison[6]={"<","<=","=",">",">=","<>"};
char *interpunction[11]={",",";",":",":=",".","(",")","{","}","[","]"};
bool search(char searchstr[],int wordtype)
{
int i;
switch (wordtype)
{
case 1:for(i=0;i<=7;i++)
{
if(strcmp(keyword[i],searchstr)==0)
return(true);
}
case 2:{
for(i=0;i<=3;i++)
{
if(strcmp(operatornum[i],searchstr)==0)
return(true);
}break;
}
case 3: {for(i=0;i<=5;i++)
{
if(strcmp(comparison[i],searchstr)==0)
return(true);
} break;
}
case 4: {for(i=0;i<=10;i++)
{
if(strcmp(interpunction[i],searchstr)==0)
return(true);
}
break;}
}
return(false);
}
char letterprocess (char ch)//字母处理函数
{
int i=-1;
char letter[20];
while (isalnum(ch)!=0)
{
letter[++i]=ch;
ch=fgetc(fp);
};
letter[i+1]='\0';
if (search(letter,1))
{
printf("<keyword:%s>\n",letter);
}
else
{
printf("<indentifier:%s>\n",letter);
}
return(ch);
}
char numberprocess(char ch)//数字处理程序
{
int i=-1;
char num[20];
while (isdigit(ch)!=0)
{
num[++i]=ch;
ch=fgetc(fp);
}
if(isalpha(ch)!=0)
{
while(isspace(ch)==0)
{
num[++i]=ch;
ch=fgetc(fp);
}
num[i+1]='\0';
printf("错误!非法标识符:%s\n",num);
goto u;
}
num[i+1]='\0';
printf("<num:%s>\n",num);
u: return(ch);
}
char otherprocess(char ch)
{
int i=-1;
char other[20];
if (isspace(ch)!=0)
{
ch=fgetc(fp);
goto u;
}
while ((isspace(ch)==0)&&(isalnum(ch)==0))
{
other[++i]=ch;
ch=fgetc(fp);
}
other[i+1]='\0';
if (search(other,2))
{ printf("<operatornum:%s>\n",other);}
else if (search(other,3))
{printf("<comparison:%s>\n",other);}
else if (search(other,4))
{ printf("<interpunction:%s>\n",other);}
else
{ printf("错误!非法字符:%s\n",other);}
u: return (ch);
}
void main ()
{
char str,c;
int i=-1;
char zhushi[200];
printf("**********************************词法分析器************************************\n");
if ((fp=fopen("ex.txt","r"))==NULL)
printf("文件无法打开!\n");
else
{
str =fgetc(fp);
while (str!=EOF)
{
if(str=='/') //判断注释
{
str=fgetc(fp);
if(str=='*')
{
str=fgetc(fp);
while(str!='*')
{ zhushi[++i]=str;
str=fgetc(fp);}
zhushi[i+1]='\0';
str=fgetc(fp);
if(str=='/')
{
printf("注释:/*%s*/\n",zhushi);}
else
str=fgetc(fp);
}
}
else
{
if (isalpha(str)!=0)
str=letterprocess(str);
else
{
if (isdigit(str)!=0)
str=numberprocess(str);
else
str=otherprocess(str);
}
}
};
printf("词法分析结束,谢谢使用!\n");
printf("点任意键退出!\n");
}
c=getch();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -