求C语言编译原理语法分析程序

(1)通过对PL0语法规则的分析,并在词法分析程序的基础上,编制语法分析程序。
(2)对于有语法和词法错误的源程序,给出出错报告。
(3)建立符号表
输入:PL0源程序
输出:(1)源程序的词法分析结果;
(2)源程序的语句类型《非常重要》
(3)符号表TABLE[ ]

#include <iostream>
using namespace std;
#define m 45
#define n 100
#define t 10
int main()
{
FILE *fp;
char filename[20],c[n];
printf("Type the file name which you want to open:");
scanf("%s",&filename);
fp=fopen(filename,"r+"); /*以r-只读方式打开指定文件*/
if((fp=fopen(filename,"r"))==NULL) /*文件不存在输出错误*/
{cout<<"文件不存在!"<<endl;exit(-1);}
cout<<"文件中内容如下:"<<endl;
for(int j=0;!feof(fp);j++){
c[j]=fgetc(fp);//从流中读取字符
}
char keyword[m][t]={"include","int","string","cout","cin","auto","break","case","char","class","const",
"continue","default","delete","do","double","else","enum","extern","float","for","friend","if","inline",
"int","long","new","operator","private","protected","public","register","return","short","sizeof","static",
"struct","switch","template","this","typedef","union","virtual","void","while"};//关键字数组
char a[t],*p=c,*q=a,*s=a;
bool w=0,r=0;
int i=0;
for(i=0;i<10;i++)a[i]=NULL;//初始化临时数组
while (*p !=NULL){
q=s=a;
if((*p>='a'&&*p<='z')||(*p>='A'&&*p<='Z')||*p=='_'){//识别标识符
*q=*p;p++;q++;
while ((*p>='a'&&*p<='z')||(*p>='A'&&*p<='Z')||(*p>='0'&&*p<='9')||*p=='_'){
*q=*p;p++;q++;
}
for(i=0;i<m;i++)if(strcmp(keyword[i],a)==0){r=1;break;}
if(r==1){cout<<"关键字为:";r=0;}
else cout<<"标识符为:";
while(s!=q){
cout<<*s;
s++;
}
cout<<endl;
for(i=0;i<t;i++)a[i]=NULL;
}
else if(*p=='\''){//识别字符常量
p++;
while(*p!='\''){

*q=*p;
p++;
q++;
}
cout<<"字符常量为:";
while(s!=q){
cout<<*s;
s++;
}
cout<<endl;
for(i=0;i<t;i++)a[i]=NULL;
p++;
}
else if(*p=='\"'){//识别字符串常量
p++;
while(*p!='\"'){
*q=*p;
p++;
q++;
}
cout<<"字符串常量为:";
while(s!=q){
cout<<*s;
s++;
}
cout<<endl;
for(i=0;i<t;i++)a[i]=NULL;
p++;
}
else if(*p=='+'||*p=='-'||*p=='*'||*p=='/'||*p=='='||*p=='%'||*p=='/'){//识别运算符
cout<<"运算符为:"<<*p;
cout<<endl;
p++;
}
else if(*p==';'||*p==','){//识别分解符
cout<<"分界符为:"<<*p;
cout<<endl;
p++;
}
else if(*p>='0'&&*p<='9'){
s=q=a;
*q=*p;p++;q++;
while(*p>='0'&&*p<='9'||*p=='.'){
*q=*p;p++;q++;
}
while(s!=q){
if(*s=='.'){w=1;break;}//识别实型常量
s++;
}
s=a;
if(w ==1){
cout<<"实型常量为:";
while(s!=q){
cout<<*s;
s++;
}
for(i=0;i<t;i++)a[i]=NULL;
}
else {
cout<<"整型常量为:";
while(s!=q){//识别整型常量
cout<<*s;
s++;
}
for(i=0;i<t;i++)a[i]=NULL;
}
cout<<endl;
}
else p++;
}
return 0;
}追问

编译出现一个错,而且这程序好像不够长,不能实现上面的所有要求吧

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-06-14
一继承的词法来自

http://blog.sina.com.cn/s/blog_67c9fc300100srad.html
二语法

用扩充的BNF表示如下:

⑴<程序>::=begin<语句串>end

⑵<语句串>::=<语句>{;<语句>}

⑶<语句>::=<赋值语句>

⑷<赋值语句>::=ID:=<表达式>

⑸<表达式>::=<项>{+<项> | -<项>}

⑹<项>::=<因子>{*<因子> | /<因子>

⑺<因子>::=ID | NUM | (<表达式>)

三要求

输入单词串,以“#”结束,如果是文法正确的句子,则输出成功信息,打印“success”,否则输出“error”。

例如:

输入 begin a:=9; x:=2*3; b:=a+x end #

输出 success!

输入 x:=a+b*c end #

输出 error!
第2个回答  2011-06-14
看书吧 谭浩强《C语言程序设计》本回答被网友采纳
相似回答