首页 > 代码库 > 词法分析

词法分析

#include <stdio.h>
#include <string.h>
#define MAX 100
main()
{
int i,j,m,n,syn;
char standard[6][10]={"begin","if","then","while","do","end"},string[MAX],token[MAX],ch;
printf("请输入一串字符,以#结尾:");
i=0;
do{
scanf("%c",&ch);
string[i]=ch;
i++;
}while(ch!=‘#‘);
string[i]=‘#‘;
i=0;
do{
for(j=0;j<8;j++)
token[j]=‘\0‘;
ch=string[i];
i++;
while(ch==‘ ‘||ch==‘\n‘){
ch=string[i];
i++;
}
j=0;
while(ch>=‘a‘&& ch<=‘z‘ || ch>=‘A‘&&ch<=‘Z‘){
token[j]=ch;
ch=string[i];
i++;
j++;
}
for(n=0;n<6;n++){
if(strcmp(token,standard[n])==0){
syn=n+1;
printf("%s,种别码%d\n",standard[n],syn);
}
}
switch(ch)
{
case ‘+‘:
token[j]=ch;
j++;
syn=13;
printf("%c,种别码%d\n",ch,syn);
break;
case ‘-‘:
token[j]=ch;
j++;
syn=14;
printf("%c,种别码%d\n",ch,syn);
break;
case ‘*‘:
token[j]=ch;
j++;
syn=15;
printf("%c,种别码%d\n",ch,syn);
break;
case ‘/‘:
token[j]=ch;
j++;
syn=16;
printf("%c,种别码%d\n",ch,syn);
break;
case ‘:‘:
token[j]=ch;
j++;
ch=string[i];
i++;
if(ch==‘=‘){
syn=18;
printf("%c%c,种别码%d\n",token[j-1],ch,syn);
}
else{
syn=17;
printf("%c,种别码%d\n",ch,syn);
}
break;
case ‘<‘:
token[j]=ch;
j++;
ch=string[i];
i++;
if(ch==‘=‘){
syn=21;
printf("%c%c,种别码%d\n",token[j-1],ch,syn);
}
else{
syn=20;
printf("%c,种别码%d\n",ch,syn);
}
break;
case ‘>‘:
token[j]=ch;
j++;
ch=string[i];
i++;
if(ch==‘=‘){
syn=24;
printf("%c%c,种别码%d\n",token[j-1],ch,syn);
}
else{
syn=23;
printf("%c,种别码%d\n",ch,syn);
}
break;
case ‘=‘:
token[j]=ch;
j++;
syn=25;
printf("%c,种别码%d\n",ch,syn);
break;
case ‘;‘:
token[j]=ch;
j++;
syn=26;
printf("%c,种别码%d\n",ch,syn);
break;
case ‘(‘:
token[j]=ch;
j++;
syn=27;
printf("%c,种别码%d\n",ch,syn);
break;
case ‘)‘:
token[j]=ch;
j++;
syn=28;
printf("%c,种别码%d\n",ch,syn);
break;
default:
break;
}
}while(ch!=‘#‘);
}

词法分析