📄 自上向下.cpp
字号:
#include <fstream.h>
#include <stdio.h>
#include <iostream.h>
#include <string.h>
char prog[80],token[8];
char ch;
int syn, p, m, n,sum,kk=0;
char *rwtab[6]={"begin","if","then","while","do","end"};
void scaner();
int Isparser();
int yucu();
int statement();
int expression();
int term();
int factor();
void main()
{
p=0;
printf("Please input :\n");
do
{
scanf("%c",&ch);
prog[p++] = ch;
}while(ch != '#');
p=0;
scaner();
Isparser();
}
void Isparser()//递归下降分析程序
{
if(syn==1)
{
scaner();
yucu();
if(syn==6)
{
scaner();
if(syn==0&&kk==0)
cout<<"success"<<endl;
}
else
{
if(kk!=1)
cout<<"error:缺end"<<endl;
kk=1;
}
}
else
{
cout<<"begin error"<<endl;//错误的开始
kk=1;
}
}
void yucu()
{
statement();
while(syn==26)
{
scaner();
statement();
}
}
void statement()
{
if(syn==10)
{
scaner();
if(syn==18)
{
scaner();
expression();
}
else {cout<<"the wrong value"<<endl;kk=1;}
}
else{cout<<"wrong sentence"<<endl;kk=1;}
}
void expression()
{
term();
while(syn==13||syn==14)
{
scaner();
term();
}
}
void term()
{
factor();
while(syn==15||syn==16)
{
scaner();
factor();
}
}
void factor()
{
if(syn==10||syn==11)
scaner();
else if(syn==27)
{
scaner();
expression();
if(syn==28)
scaner();
else {cout<<") error"<<endl;kk=1;}//')'错误
}
else{cout<<"error expression"<<endl;kk=1;}//表达式错误
}
void scaner()
{
for(int k=0;k<8;k++) token[k]=NULL;
ch=prog[p++]; m=0;
while(ch==' ') ch=prog[p++];
if(ch>='a'&& ch<='z'||ch>='A' &&ch<='Z')
{
while(ch>='a'&&ch<='z'||ch>='0' &&ch<='9'||ch>='A' &&ch<='Z')
{
token[m++]=ch;
ch =prog[p++];
}
token[m++]='\0';
--p;
syn=10;
for(n=0;n<6;n++)
if(strcmp(token,rwtab[n])==0)
{ syn =n+1;
break;
}
}
else
if(ch>='0' &&ch<='9')
{
while(ch>='0' &&ch<='9')
{sum=sum*10+ch-'0';
ch=prog[p++];
}
--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; --p;}
break;
case'>':token[m++]=ch;
ch=prog[p++];
if(ch=='=')
{
syn=24;
token[m++]=ch;
}
else
{ syn=23; --p; }
break;
case':':token[m++]=ch;
ch=prog[p++] ;
if(ch=='=')
{ syn=18;
token[m++]=ch;
}
else
{syn=17 ;
--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;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -