#include <stdio.h>
#include <math.h>
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
#define M 100
#define N 50
char bsf[N][N],gjz[N][N],jf[N];
int n=0;
int m=0;
int p=0;
void identity(char c[M])
{
int i=0;
int j=0;
int l;
int t=0;
char s[M];
l=strlen(c);
while(i<l)
{
if(c[i]>='a'&&c[i]<='z'||c[i]>='A'&&c[i]<='Z')
{
s[j]=c[i];
i++;
j++;
while (c[i]>='a'&&c[i]<'z'||c[i]>='A'&&c[i]<='Z')
{s[j++]=c[i++];}
s[j]='\0';
if (strcmp(s,"main")==0||strcmp(s,"printf")==0||strcmp(s,"int")==0
||strcmp(s,"for")==0||strcmp(s,"while")==0||strcmp(s,"if")==0||strcmp(s,"char")==0)
{
while (t<n&&strcmp(gjz[t],s)!=0)
{t++;}
if(t==n) strcpy(gjz[n++],s);
cout<<"关键字: "<<s<<endl;
t=0;
}
else
{
while (t<m&&strcmp(bsf[t],s)!=0)
{t++;}
if(t==m) strcpy(bsf[m++],s);
cout<<"标示符: "<<s<<endl;
t=0;
}
j=0;
}
else if (c[i]>='0'&&c[i]<='9'){
s[j]=c[i];
i++;
j++;
while (c[i]>='0'&&c[i]<'9'||c[i]=='.')
{s[j++]=c[i++];}
s[j]='\0';
cout<<"数字: "<<s<<endl;
j=0;
}
else if(c[i]=='<'||c[i]=='>'||c[i]=='+'||c[i]=='-'||c[i]=='*'||c[i]=='/'||c[i]=='='||c[i]=='&')
{
printf("运算符: ");
printf("%c",c[i]);
if(c[i+1]=='=')
{
printf("%c",c[i+1]); i++;
}
printf("\n");
i++;
}
else if(c[i]==','||c[i]==';'||c[i]=='('||c[i]=='_'||c[i]==')'||c[i]=='{'||c[i]=='}'||c[i]=='['||c[i]==']'||c[i]=='"'||c[i]=='&'||c[i]=='!')
{
printf("界符: ");
printf("%c",c[i]);
printf("\n");
while (t<p&&jf[t]!=c[i])
{t++;}
if(t==p) jf[p++]=c[i];
i++;
t=0;
}
else if(c[i]=='%'&&c[i+1]=='d'||c[i]=='%'&&c[i+1]=='c'){
printf("关键字: ");
gjz[n][0]=c[i];
printf("%c",c[i++]);
gjz[n++][1]=c[i];
printf("%c",c[i++]);
printf("\n");
}
}
}
void main()
{
FILE *fp;
char yl[M];
int i;
cout<<"\nz******************************词 法 分 析 **************************************"<<endl;
cout<<"***************************************制作人:杨玲(0215172)******************"<<endl;
fp=fopen("c.txt","r");
fscanf(fp,"%s",yl);
do
{
printf("\n********************* # 分 行 词 法 分 析 # ***********************************\n");
cout<<"源代码: "<<yl<<"\n"<<endl;
identity(yl);
fscanf(fp,"%s",yl);
}while(! feof(fp));
printf("\n********************* # 词 法 分 析 结 束 # ***********************************\n");
printf("\n**************** # 关键字表,表示符表和界符表如下 : # ************************\n\n");
cout<<"此程序中的关键字有:"<<endl;
for(i=0;i<n;i++)
cout<<" "<<gjz[i];
cout<<"\n此程序中的表示符有:"<<endl;
for(i=0;i<m;i++)
cout<<" "<<bsf[i];
cout<<"\n此程序中的界符有:"<<endl;
for(i=0;i<p;i++)
cout<<" "<<jf[i];
cout<<endl;
}