求一个词法程序

free1879 2005-12-20 04:53:52
词法分析难度太大,刚学编译原理!看看各位怎么写的...
...全文
108 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
derekchuang 2005-12-21
  • 打赏
  • 举报
回复
/******************************************************************
*此程序只具备对简单的C语言程序的词法分析,不具备出错处理等高级功能*
*
*
*
*******************************************************************/
#include<stdio.h>
#include<string.h>

FILE *fp;
char ch; //存放最新读进的源程序字符


//将下一个输入字符读到ch中,搜索指示器前移一字符位置
GetChar(){
fscanf(fp,"%c",&ch);
}

//判断ch中的字符是否为空白
int IsEmpty(){
if(ch==' '||ch=='\t'||ch=='\n')
return 1;
else return 0;
}

//判断ch是否为字母
int IsLetter(){
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
return 1;
else return 0;
}
//判断ch是否为数字
int IsDigit(){
if(ch>='0'&&ch<='9')
return 1;
else return 0;
}

//判断ch是否为分隔符
int IsCompart(){
if(ch=='('||ch==')'||ch=='{'||ch=='}'||ch==','||ch==';'||ch=='"')
return 1;
else return 0;
}

//判断ch是否为运算符
int IsOperation(){
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='='||ch=='%'||ch=='<'||ch=='>')
return 1;
else return 0;
}

//是否为保留字
int IsKeyWord(char *c){
if(c=="int"||c=="for"||c=="if")
return 1;
else return 0;
}

//初始化单词符号字符串
Init(char *c){
int i;
for(i=0;i<10;i++)
c[i]='\0';
}


main(){

int i=0,j;
char strToken[10]; //存放构成单词符号的字符串
if((fp=fopen("E:\\编译原理\\a.txt","r"))==NULL){
printf("打开文件出错!\n" );
exit(1);
}
GetChar();
for(j=0;ch!='#';j++){
if(IsEmpty()){
while(IsEmpty()){
GetChar();
}
}
if(IsLetter()){
while(IsLetter()||IsDigit()){
strToken[i]=ch;
i++;
GetChar();
}
strToken[i]='\0';
if(IsKeyWord(strToken))
printf("<%s,保留字>\n",strToken);
else
printf("<%s,标识符>\n",strToken);
Init(strToken);
i=0;
}
if(IsCompart()){
while(IsCompart()){
printf("<%c,分隔符>\n",ch);
GetChar();
}
}
if(IsDigit()){
while(IsDigit()){
strToken[i]=ch;
i++;
GetChar();
}
strToken[i]='\0';
printf("%<s,数字>\n",strToken);
Init(strToken);
i=0;
}
if(IsOperation()){
while(IsOperation()){
strToken[i]=ch;
i++;
GetChar();
}
strToken[i]='\0';
printf("<%s,运算符>\n",strToken);
Init(strToken);
i=0;
}
}
getch();
fclose(fp);
}

sankt 2005-12-21
  • 打赏
  • 举报
回复
http://www.08090.com/c/sr/showart.asp?art_id=5&cat_id=2
http://www.qcode.org/article/qcode/code5/cj/cj4/200511/12392.html
其实这方面的例子很多,可以看看上面的参考一下

69,372

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧