#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
char ch=' ',strToken[20]={'\0'};
int k=0,flag;//该词法器可识别:字母数字串、数字串、基本符号(+-/*=<>;,)
void GetChar()
{
ch=getchar();
}
void GetBC()
{
while(ch==' ')
{GetChar();flag=1;}
}
void Concat()
{
strToken[k++]=ch;
}
int IsLetter()
{
return isalpha(ch);
}
int IsDigit()
{
return isdigit(ch);
}
int f=1;
void return1(int no,char s[])
{
if(f==1)
printf("输出:\n");f++;
printf(" (%d,%s)\n",no,s);
strToken[0]='\0';k=0;
}
void return2(int no,char c)
{
if(f==1)
printf("输出:\n");f++;
printf(" (%d,%c)\n",no,c);
}
void scanner()
{
if(IsLetter())
{
while(IsLetter()||IsDigit())
{
Concat();GetChar();
}
flag=1;strToken[k]='\0';
return1(1,strToken);
}
else if(IsDigit())
{
while(IsDigit())
{
Concat();GetChar();
}
flag=1;strToken[k]='\0';
return1(2,strToken);
}
else if(ch=='=')
{
int kk=1;
while(ch=='='&&kk!=3)
{
Concat();GetChar();kk++;
}
flag=1;strToken[k]='\0';
return1(3,strToken);
}
else if(ch=='+')
{
return2(11,'+');
}
else if(ch=='-')
{
return2(12,'-');
}
else if(ch=='*')
{
return2(13,'*');
}
else if(ch=='/')
{
return2(14,'/');
}
else if(ch=='<')
{
return2(15,'<');
}
else if(ch=='>')
{
return2(16,'>');
}
else if(ch=='(')
{
return2(17,'(');
}
else if(ch==')')
{
return2(18,')');
}
else if(ch==':')
{
return2(19,':');
}
else if(ch==';')
{
return2(20,';');
}
else if(ch==',')
{
return2(21,',');
}
else if(ch==' ')
GetBC();
else exit(0);
}
void main()
{
printf("输入:");
GetChar();GetBC();
while(ch)
{
flag=0;
scanner();
GetBC();
if(flag==0) GetChar();//flag为1时,不执行GetChar()
}
scanf("%d");
}
词法分析器
最新推荐文章于 2024-07-02 22:22:32 发布