#include<stdio.h>
#include<string.h>
#define MAX 100
int
n=0,i=0;
char
*keyshuru[6]={
"begin"
,
"if"
,
"then"
,
"while"
,
"do"
,
"end"
};
void
KEYword(
char
shuru[MAX])
{
int
k=0,key=0,q=1;
char
token[MAX];
while
(shuru[i]!=
'#'
)
{
while
((shuru[i]>=
'a'
&&shuru[i]<=
'z'
) || (shuru[i]>=
'A'
&&shuru[i]<=
'Z'
) || (shuru[i]>=
'0'
&& shuru[i]<=
'9'
))
{
if
((shuru[i]>=
'a'
&&shuru[i]<=
'z'
) || (shuru[i]>=
'A'
&&shuru[i]<=
'Z'
) || (shuru[i]>=
'0'
&& shuru[i]<=
'9'
))
{
token[n]=shuru[i];
n++;
token[n]=
' '
;
i++;
if
(shuru[i]>=
'0'
&& shuru[i]<=
'9'
)
q++;
}
for
(k=0;k<6;k++)
{
key=0;
if
(strcmp(keyshuru[k],token)==0)
{
printf(
"%s %d
"
,keyshuru[k],k+1);
key=1;
break
;
}
} }
if
((shuru[i-q]>=
'a'
&&shuru[i-q]<=
'z'
)||(shuru[i-q]>=
'A'
&&shuru[i-q]<=
'Z'
))
{
if
(key==0)
{
printf(
"%s 10
"
,token);
}
}
key=1;
i=i+1;
n=0;
}
}
void
character(
char
shuru[MAX])
{
int
p=0,sign=0;
for
(p=0;p<MAX;p++)
{
switch
(shuru[p])
{
case
'+'
:
printf(
"+ 13
"
);
break
;
case
'-'
:
printf(
"- 14
"
);
break
;
case
'*'
:
printf(
"* 15
"
);
break
;
case
'/'
:
printf(
"/ 16
"
);
break
;
case
':'
:
if
(shuru[p+1]==
'='
)
{
printf(
":= 18
"
);
p++;
}
else
printf(
": 17
"
);
break
;
case
'<'
:
if
(shuru[p+1]==
'='
)
{
printf(
"<= 21
"
);
sign=1;
p++;
}
else
if
(shuru[p+1]==
'>'
)
{
printf(
"<> 22
"
);
sign=1;
p++;
}
else
if
(sign==0)
printf(
"< 20
"
);
break
;
case
'>'
:
if
(shuru[p+1]==
'='
)
{
printf(
">= 24
"
);
p++;
}
else
printf(
"> 23
"
);
break
;
case
'='
:
printf(
"= 25
"
);
break
;
case
';'
:
printf(
"; 26
"
);
break
;
case
'('
:
printf(
"( 27
"
);
break
;
case
')'
:
printf(
") 28
"
);
break
;
case
'#'
:
printf(
"# 29
"
);
break
;
}
}
}
void
number(
char
shuru[MAX])
{
int
p=0,j=0,t=0,key=0,q=1;
char
num[MAX];
while
(shuru[p]!=
'#'
)
{
key=0;
j=0;
while
(shuru[p]>=
'0'
&& shuru[p]<=
'9'
)
{
num[j]=shuru[p];
p++;
j++;
key=1;
q++;
}
if
((shuru[p-q]>=
'a'
&&shuru[p-q]<=
'z'
)||(shuru[p-q]>=
'A'
&&shuru[p-q]<=
'Z'
))
{
key=0;
q=1;
}
if
(key==1)
{
for
(t=0;t<j;t++)
{
printf(
"%c"
,num[t]);
}
printf(
" 11
"
);
j=0;
}
p++;
}
}
main()
{
char
a;
char
shuru[MAX];
int
p=0,j=0,m=0;
printf(
"请输入源程序,#键为结束标志:"
);
do
{
scanf(
"%c"
,&a);
shuru[p]=a;
p++;
}
while
(a!=
'#'
);
KEYword(shuru);
character(shuru);
number(shuru);
}
![](https://images2015.cnblogs.com/blog/809058/201509/809058-20150921183841553-2016957416.png)