#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[85], s[85];
int i, j, len;
memset(str,0,sizeof(str));
while(gets(str) != NULL)
{
len = strlen(str);
j = 0;
memset(s, 0, sizeof(s));
for(i = 0; i < len; i++)
{
if((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z'))
{
for(; i < len; i++)
{
if((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= '0' && str[i] <= '9'))
{
s[j++] = str[i];
}
else
{
break;
}
}
s[j] = '\0';
if(strcmp(s,"main") == 0 || strcmp(s,"if") == 0 || strcmp(s,"else") == 0 || strcmp(s,"for") == 0 || strcmp(s,"while") == 0 || strcmp(s,"int") == 0)
{
printf("(keyword,%s)\n",s);
}
else
{
printf("(identifier,%s)\n",s);
}
memset(s,0,sizeof(s));
j = 0;
i = i - 1;
}
else if(str[i] == '(' || str[i] == ')' || str[i] == '{' || str[i] == '}' || str[i] == ',' || str[i] == ';')
{
printf("(boundary,%c)\n",str[i]);
}
else if(str[i] >= '0' && str[i] <= '9')
{
for(; i < len; i++)
{
if(str[i] >= '0' && str[i] <= '9')
{
s[j++] = str[i];
}
else
{
break;
}
}
s[j] = '\0';
printf("(integer,%s)\n",s);
memset(s,0,sizeof(s));
j = 0;
i = i - 1;
}
else if(str[i] == '=' || str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/' || str[i] == '<' || str[i] == '>' || str[i] == '!')
{
if(i == len - 1)
{
printf("(operator,%c)\n",str[i]);
}
else
{
if(str[i + 1] == '=')
{
printf("(operator,%c%c)\n",str[i],str[i + 1]);
i += 1;
}
else
{
printf("(operator,%c)\n",str[i]);
}
}
}
}
memset(str,0,sizeof(str));
}
return 0;
}
小C语言--词法分析程序
最新推荐文章于 2021-10-27 19:45:14 发布