0917 词法分析

#include<stdio.h>
#include<string.h>
char input[200];
char token[5];
char ch;
int p;
int fg;
int num;
char index[6][6]={"begin","if","then","while","do","end"};
main()
{
p=0;
printf("please intput string(End with '#'):\n");
do
{
ch=getchar();
input[p++]=ch;
}while(ch!='#');
p=0;
do
{
scaner();
switch(fg)
{
case 11:printf("( %d,%d ) ",fg,num);break;
case -1:printf("input error\n"); break;
default:printf("( %d,%s ) ",fg,token);
}
}while(fg!=0);
getch();
}
scaner()
{
int m=0;
int n;
for(n=0;n<5;n++)
token[n]=NULL;
ch=input[p++];
while(ch==' ')ch=input[p++];
if((ch<='z'&&ch>='a')||(ch<='Z'&&ch>='A'))
{
while((ch<='z'&&ch>='a')||(ch<='Z'&&ch>='A')||(ch<='9'&&ch>='0'))
{
token[m++]=ch;
ch=input[p++];
}
token[m++]='\0';
ch=input[--p];
fg=10;
for(n=0;n<6;n++)
if(strcmp(token,index[n])==0)
{
fg=n+1;
break;
}
}
else if((ch<='9'&&ch>='0'))
{
num=0;
while((ch<='9'&&ch>='0'))
{
num=num*10+ch-'0';
ch=input[p++];
}
ch=input[--p];
fg=11;
}
else
switch(ch)
{
case '<':
m=0;
token[m++]=ch;
ch=input[p++];
if(ch=='>')
{
fg=21;
token[m++]=ch;
}
else if(ch=='=')
{
fg=22;
token[m++]=ch;
}
else
{
fg=20;
ch=input[--p];
}
break;
case '>':
token[m++]=ch;
ch=input[p++];
if(ch=='=')
{
fg=24;
token[m++]=ch;
}
else
{
fg=23;
ch=input[--p];
}
break;
case ':':
token[m++]=ch;
ch=input[p++];
if(ch=='=')
{
fg=18;
token[m++]=ch;
}
else
{
fg=17;
ch=input[--p];
}
break;
case '+':fg=13;token[0]=ch;break;
case '-':fg=14;token[0]=ch;break;
case '*':fg=15;token[0]=ch;break;
case '/':fg=16;token[0]=ch;break;
case ':=':fg=18;token[0]=ch;break;
case '<>':fg=21;token[0]=ch;break;
case '<=':fg=22;token[0]=ch;break;
case '>=':fg=24;token[0]=ch;break;
case '=':fg=25;token[0]=ch;break;
case ';':fg=26;token[0]=ch;break;
case '(':fg=27;token[0]=ch;break;
case ')':fg=28;token[0]=ch;break;
case '#':fg=0;token[0]=ch;break;
default:fg=-1;
}
}

你可能感兴趣的:(0917 词法分析)