词法分析程序(C)

#include <stdio.h>
#include <string.h> char string[],word[],ch;
int type,p,i,n,sum;
char keyword[][]={"begin","if","then","while","do","end"}; //关键字数组 void scaner(void); main()
{
p=;
printf("\n\n请输入一个程序段(以'#'结束):\n");
do{
scanf("%c",&ch);
string[p++]=ch;
}while(ch!='#');
printf("单词符号\t种别码 \n");
p=;
do{
scaner();
switch(type)
{
case :
printf(" %-10d%5d\n",sum,type);
break;
case -:
printf("有无法识别的字符\n");
return ;
break;
default:
printf(" %-10s%5d \n",word,type);
break;
}
}while(type!=);
} void scaner(void)
{
sum=;
for(i=;i<;i++)
word[i++]= NULL; ch=string[p++];
i=; while((ch==' ')||(ch=='\n'))
ch=string[p++]; if(((ch<='z')&&(ch>='a'))||((ch<='Z')&&(ch>='A')))
{
while(((ch<='z')&&(ch>='a'))||((ch<='Z')&&(ch>='A'))||((ch>='')&&(ch<='')))
{
word[i++]=ch;
ch=string[p++];
} p--;
type=; //先将以字母开头的字符识别为标识符 for(n=;n<;n++)
if(strcmp(word,keyword[n])==) //关键字数组比较,相同则表示为关键字,种别码即为下标值加一
{
type=n+;
break;
}
} else if((ch>='')&&(ch<=''))
{
while((ch>='')&&(ch<=''))
{
sum=sum*+ch-''; //将字符型转化为整形sum
ch=string[p++];
}
p--;
type=;
} else //else语句内识别除关键字、标识符、数字以外的其他字符
{
switch(ch)
{
case '+':
type=;
word[i++]=ch;
break; case '-':
type=;
word[i++]=ch;
break; case '*':
type=;
word[i++]=ch;
break; case '/':
type=;
word[i++]=ch;
break; case ':':
word[i++]=ch;
ch=string[p++];
if(ch=='=')
{
type=;
word[i++]=ch;
}
else
{
type=;
p--;
}
break; case '<':
word[i++]=ch;
ch=string[p++];
if(ch=='=')
{
type=;
word[i++]=ch;
}
else
{
type=;
p--;
}
break; case '>':
word[i++]=ch;
ch=string[p++];
if(ch=='=')
{
type=;
word[i++]=ch;
}
else
{
type=;
p--;
}
break; case '=':
type=;
word[i++]=ch;
break; case ';':
type=;
word[i++]=ch;
break; case '(':
type=;
word[i++]=ch;
break; case ')':
type=;
word[i++]=ch;
break; case '#':
type=;
word[i++]=ch;
break; default:
type=-;
break;
}
}
word[i++]='\0'; //word字符数组变字符串
}
上一篇:asp.net时间范围查询


下一篇:Android通过URL加载网络图片