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

发布网友 发布时间:2022-04-23 07:32

我来回答

3个回答

热心网友 时间:2022-06-17 18:00

#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;
}追问编译出现一个错,而且这程序好像不够长,不能实现上面的所有要求吧

热心网友 时间:2022-06-17 18:00

一继承的词法来自

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!

热心网友 时间:2022-06-17 18:01

看书吧 谭浩强《C语言程序设计》

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com