📄 2.c
字号:
#include "stdio.h"
int flag=1;
int ZT=1;
int k=0,j=0,l=0;
char Stack[10]={'\0'};
char S[80]={'\0'};
char T[100]={'\0'};
char top,coda,tp;
char bring[12][10]={"error\n","E-> TA\n","A-> +TA\n",
"A-> -TA\n","T-> PB\n","B-> *PB\n","B-> /PB\n","P-> c\n",
"P-> i\n","A->empty\n","B->empty\n","\n"};
void Push()
{
Stack[k]=tp;top=tp; k++;
}
void Pop()
{
k--; Stack[k]='\0';top=Stack[k-1];
}
void Next()
{
coda=S[j];j++;
}
void g()
{
int i=0;
while(S[i]!='\0'&&S[i]!=' ')
i++;
S[i]='#';
}
void copy(int n)
{
int i;
for(i=0;i<10;i++,l++)
T[l]=bring[n][i];
if(n==0) ZT=0;
}
void emptyST()
{int i;
for(i=0;i<100;i++)
{S[i]='\0';T[i]='\0';}
}
void display(int n)
{
int i;
for(l=0;l<k;l++) T[l]=Stack[l];
while(l<10) {T[l]=' ';l++;}
for(i=0;i<j-1;i++,l++) T[l]=' ';
for(;S[i]!='\0';i++,l++) T[l]=S[i];
while(l<30) {T[l]=' ';l++;}
copy(n);printf("%s",T);
}
void match(char a,char b)
{
if(a==b)
if(a=='#'){flag=0;return;}
else
{Pop();Next();display(11);flag=1;return;}
else
switch(a)
{case 'E':
switch(b)
{case 'c':
case 'i':
{ Pop();
tp='A';Push();
tp='T';Push(); /* E-> TA */
display(1);
break;
}
case '#':{Pop();display(11);break;}
default:{Next();display(0);} /* error */
}
break;
case 'A':
switch(b)
{case'+':
{ tp='T';Push();
tp='+';Push(); /* A-> +TA */
display(2);
break;
}
case '-':
{ tp='T';Push();
tp='-';Push(); /* A-> -TA */
display(3);
break;
}
case '#':{Pop();display(9);break;} /* A->empty */
default:{Next();display(0);} /* error */
}
break;
case 'T':
switch(b)
{case 'c':
case 'i':
{ Pop();
tp='B';Push();
tp='P';Push(); /* T-> PB */
display(4);
break;
}
case '+':
case '-':
case '#': {Pop();display(0);break;} /* error */
default:{Next();display(0);} /* error */
}
break;
case 'B':
switch(b)
{case '*':
{ tp='P';Push();
tp='*';Push(); /* B-> *PB */
display(5);
break;
}
case '/':
{ tp='P';Push();
tp='/';Push(); /* B-> /PB */
display(6);break;
}
case '+':
case '-':
case '#':{Pop();display(10);break;} /* B->empty */
default:{Next();display(0);} /* error */
}
break;
case 'P':
switch(b)
{case 'c':
{ Pop();
tp='c';Push(); /* P-> c */
display(7);break;
}
case 'i':
{ Pop();
tp='i';Push(); /* P-> i */
display(8);break;
}
default:{Pop();display(0);} /* error */
}
}
flag=1;return;
}
main()
{
char i='1'; int w=0;
char buf[10][12]={"E->TA","A->+TA","A->-TA","A->e","T->PB","B->*PB","B->/PB","B->e","P->c","P->i"};
printf("This Program Analysis Excepssions in the following grammer:\n");
for (;w<10;w++){
printf("%s ",buf[w]);
if ((w+1)%4==0) printf("\n");
}
printf("E:expression, c:const, i:identifier.\n");
printf("input an expression:\n");
scanf("%s",S);
while(S[0]!='#') {
k=0;j=0;flag=1;
tp='#';Push();
tp='E';Push();
g();
Next();
display(11);
while(flag)
{
match(top,coda);
}
if(ZT)
{
printf("Correct Excepssion!\n");
}
else
{
printf("Wrong Excepssion!\n");
}
emptyST(); i++;ZT=1;
printf("input an expression:\n");
scanf("%s",S);
if(S[0]=='#') exit(0);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -