📄 cifa.cpp
字号:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>//与字符相关的处理函数
#include <malloc.h>
#define NULL 0
FILE *fp;
char ch;
char *keyword[5]={"DIM","IF","DO","STOP","END"};
char *charactor[11]={"=","+","*","(",")",",","[","]",";","{","}"};
//////////////////////////////////////////////////////////////////////////////////////////
bool search(char searchs[],int wordtype)//判断是否searchs[]属于关键字或符号
{
int i;
switch (wordtype)
{
case 1://关键字
for(i=0;i<5;i++)
{
if(strcmp(keyword[i],searchs)==0)
return(true);
}
break;
case 2://符号
for(i=0;i<11;i++ )
{
if(strcmp(charactor[i],searchs)==0)
return(true);
}
break;
}
return(false);
}
///////////////////////////////////////////////////////////////////////////////////////////
char letterprocess (char ch)//字母处理函数
{
int i=0;
char letter[20];
while (isalnum(ch)!=0&&ch!=EOF)//判断ch是否为数字或字母,当是时循环,直至不是数字或字母
{
letter[i]=ch;
ch=fgetc(fp);
i++;
}
letter[i]='\0';//在串后加结束符
if (search(letter,1))
printf("<%s,->\n",letter);
else
printf("<indentifier,%s>\n",letter);
return(ch);
}
///////////////////////////////////////////////////////////////////////////////////////////
char numberprocess(char ch)//数字处理程序
{
int i=0;
char num[20];
while (isdigit(ch)!=0)//是数字时循环
{
num[i]=ch;
ch=fgetc(fp);
i++;
}
if(isalpha(ch)!=0)//是否为英文字母
{
while(isspace(ch)==0&&ch!=EOF)//不为空格时
{
num[i]=ch;
ch=fgetc(fp);
i++;
}
num[i]='\0';
printf("错误!非法标识符:%s\n",num);
goto u;
}
num[i]='\0';
printf("<num,%s>\n",num);
u: return(ch);
}
//////////////////////////////////////////////////////////////////////////////////////////////
char otherprocess(char ch)
{
int i=0;
char other[20];
if (isspace(ch)!=0)
goto u;
while ((isspace(ch)==0)&&(isalnum(ch)==0)&&ch!=EOF)
{
other[i]=ch;
ch=fgetc(fp);
i++;
}
other[i]='\0';
if (search(other,2))
printf("<relop,%s>\n",other);
else if (search(other,3))
printf("<%s,->\n",other);
else if (search(other,4))
printf("<%s,->\n",other);
else
printf("错误!非法字符:%s\n",other);
u: return (ch);
}
/////////////////////////////////////////////////////////////////////////////////////////////
void main ()
{
char s;
printf("**********************************词法分析器************************************\n");
if ((fp=fopen("源程序.txt","r"))==NULL)
printf("源程序无法打开!\n");
s=fgetc(fp);
while(s!=EOF)
{
//从文件中读取一个字符
if(isspace(s)!=0)
{
s=fgetc(fp);
}
if (isalpha(s)!=0)//判断为字母时
s=letterprocess(s);
else
{
if (isdigit(s)!=0)//为数字时
s=numberprocess(s);
else
s=otherprocess(s);
}
}
printf("词法分析结束,谢谢使用!\n");
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -