?? 語法分析.cpp
字號:
#include "stdio.h"
#include "string.h"
#include "conio.h"
#include "ctype.h"
char prog[80],
token[8]; /*存放構成單詞符號的字符串*/
char ch;
int syn, /*存放單詞字符的種別碼*/
n,
kk,
sum, /*存放整數型單詞*/
m,p; /*p是緩沖區prog的指針,m是token的指針*/
char *rwtab[6]={"begin","if","then","while","do","end"}; /*關鍵字*/
void scaner();
void lrparser();
void yucu();
void statement();
void expression();
void factor();
void term();
void scaner()
{
m=0;
sum=0;
for(n=0;n<8;n++) token[n]='\0';
ch=prog[p++];
while(ch==' ') ch=prog[p++];
if(isalpha(ch)) /*判斷ch為字母字符*/
{
while(isalpha(ch)||isdigit(ch)) /*判斷ch 為字母字符或者數字字符*/
{
token[m++]=ch;
ch=prog[p++];}
token[m++]='\0';
ch=prog[p--];
syn=10;
for(n=0;n<6;n++)
if(strcmp(token,rwtab[n])==0) /*字符串的比較*/
{
syn=n+1;
break;
}
}
else
if(isdigit(ch)) /*判斷ch是數字字符*/
{
while(isdigit(ch)) /*判斷ch是數字字符*/
{
sum=sum*10+ch-'0';
ch=prog[p++];
}
ch=prog[p--];
syn=11;}
else
switch(ch)
{
case'<':m=0;
token[m++]=ch;
ch=prog[p++];
if(ch=='>')
{
syn=21;
token[m++]=ch;
}
else if(ch=='=')
{
syn=22;
token[m++]=ch;
}
else
{
syn=20;
ch=prog[p--];
}
break;
case'>':m=0;
token[m++]=ch;
ch=prog[p++];
if(ch=='=')
{
syn=24;
token[m++]=ch;
}
else
{
syn=23;
ch=prog[p--];
}
break;
case':':m=0;
token[m++]=ch;
ch=prog[p++];
if(ch=='=')
{
syn=18;
token[m++]=ch;
}
else
{
syn=17;
ch=prog[p--];
}
break;
case'+':syn=13;token[0]=ch;break;
case'-':syn=14;token[0]=ch;break;
case'*':syn=15;token[0]=ch;break;
case'/':syn=16;token[0]=ch;break;
case'=':syn=25;token[0]=ch;break;
case';':syn=26;token[0]=ch;break;
case'(':syn=27;token[0]=ch;break;
case')':syn=28;token[0]=ch;break;
case'#':syn=0;token[0]=ch;break;
default:syn=-1;
}
}
void lrparser()
{
if(syn==1)
{
scaner();
yucu();
if(syn==6)
{
scaner();
if(syn==0 && (kk==0))
printf("success");
}
}
else
{
printf("error");
kk=1;
}
return;
}
void yucu()
{
statement();
while(syn==26)
{
scaner();
statement();
}
return;
}
void statement()
{
if(syn==10)
{
scaner();
if(syn==18)
{
scaner();
expression();
}
else
{
printf("\":=\" ERROR!");
kk=1;
}
}
else
{
printf("statement ERROR!");
kk=1;
}
return;
}
void expression()
{
term();
while(syn==13 || syn==14)
{
scaner();
term();
}
return;
}
void term()
{
factor();
while(syn==15 || syn==16)
{
scaner();
factor();
}
return;
}
void factor()
{
if(syn==10 || syn==11)
scaner();
else if(syn==27)
{
scaner();
expression();
if(syn==28)
scaner();
else
{
printf("\')\' ERROR!");
}
}
else
{
printf("expressions ERROR!");
kk=1;
}
return;
}
void main()
{
kk=0;
printf("When input a \'#\' at the end of an line,this programe will be over.\n");
printf("And the programe will output the codes you inputed just now.\n");
p=0;
printf("\nplease input string:\n");
do {
ch=getchar();
prog[p++]=ch;
}while(ch!='#');
p=0;
scaner();
lrparser();
getch();
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -