编译原理词法分析器c++源程序


#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<process.h> /*头文件*/

   void init();
      char *DchangeB(char *buf);
   int search(char *buf,int type,int command);
      void intdeal(char *buffer);
      void chardeal(char *buffer);
   void errordeal(char error,int lineno);
   void scanner();

void init()
{      char *key[]={"","auto","break","case","char","const","continue","default","do","double",
                 "else","enum","extern","float","for","goto","if","int","long","register",
                 "return","short","signed","sizeof","static","struct","switch","typedef",
                 "union","unsigned","void","volatile","while"};     /*C语言所有关键字/
    char *limit[]={" ","(",")","[","]","->",".","!","++","--","&","~",
                   "*","/","%","+","-","<<",">>","<","<=",">",">=","==","!=","&&","||",
                  "=","+=","-=","*=","/=",",",";","{","}","#","_","'"};/*运算、限界符*/
 fstream outfile;
    int i,j;
 char *c;
 outfile.open("key.txt",ios::out);
 for(i=0;i<32;i++)
  outfile<<key[i]<<endl;
 outfile.close();
 outfile.open("Limit.txt",ios::out);
 for(j=0;j<38;j++)
  outfile<<limit[j]<<endl;
 c="";
 outfile<<c;
 outfile.close();
 outfile.open("bsf.txt",ios::out);
 outfile.close();
 outfile.open("cs.txt",ios::out);
 outfile.close();
 outfile.open("output.txt",ios::out);
 outfile.close();
}

char *DchangeB(char *buf)
{
      
    int temp[20];
 char *binary;
 int value=0,i=0,j;
 for(i=0;buf[i]!='/0';i++)
  value=value*10+(buf[i]-48);       /*将字符转化为十进制数*/
    if(value==0)
    {
  binary=new char[2];
  binary[0]='0';
  binary[1]='/0';
  return(binary);
 }
 i=0;
 while(value!=0)
    {
  temp[i++]=value%2;
  value/=2;
 }
 temp[i]='/0';
 binary=new char[i+1];
 for(j=0;j<=i-1;j++)
       binary[j]=(char)(temp[i-j-1]+48);
    binary[i]='/0';
    return(binary);  /*十进制转化为二进制*/

}

int search(char *buf,int type,int command)
{ int number=0;
    fstream outfile;
    char ch;
    char temp[30];
    int i=0;
    switch(type)
    {
 case 1: outfile.open("key.txt",ios::in);break;
    case 2: outfile.open("bsf.txt",ios::in);break;
    case 3: outfile.open("cs.txt",ios::in);break;
    case 4: outfile.open("limit.txt",ios::in);break;
    }
 outfile.get(ch);
 while(ch!=EOF){
     while(ch!='/n')
        {
            temp[i++]=ch;
            outfile.get(ch);
        }
        temp[i]='/0';
        i=0;
        number++;
        if(strcmp(temp,buf)==0)
        { 
      outfile.close();
   return number;        /*若找到,返回在相应表中的序号*/
        }
        else
          outfile.get(ch);
 }                           //结束外层while循环
     if(command==1)
     {  
      outfile.close( );
   return 0;                /*找不到,当只需查表,返回0,否则还需造表*/
    
  }
switch(type)
    {
 case 1: outfile.open("key.txt",ios::in);break;
    case 2: outfile.open("bsf.txt",ios::in);break;
    case 3: outfile.open("cs.txt",ios::in);break;
    case 4: outfile.open("limit.txt",ios::in);break;
    }
outfile<<buf;
outfile.close();
 return number+1;
}


void intdeal(char *buffer){

  fstream outfile;
    int result;
    result=search(buffer,1,1);           /*先查关键字表*/
    outfile.open("output.txt",ios::app);
    if(result!=0)
       outfile<<buffer<<result<<endl;  /*若找到,写入输出文件*/
    else
    {
        result=search(buffer,2,2);       /*若找不到,则非关键字,查标识符表,还找不到则造入标识符表*/
        outfile<<buffer<<result<<endl;
    }                                 /*写入输出文件*/
    outfile.close();
}

void chardeal(char *buffer)
{    fstream outfile;
    int result;
    result=search(buffer,1,1);           /*先查关键字表*/
 outfile.open("output.txt",ios::app);
    if(result!=0)
       outfile<<buffer<<result<<endl;   /*若找到,写入输出文件*/
    else
    {
        result=search(buffer,2,2);       /*若找不到,则非关键字,查标识符表,还找不到则造入标识符表*/
       outfile<<buffer<<result<<endl;
    }                                 /*写入输出文件*/
    outfile.close();
}

void errordeal(char error,int lineno)
{  cout<<"/nerror: "<<error<<" ,line"<<lineno;
}

void scanner()
{   fstream  infile,outfile;
    char filename[20];
    char ch;
 int err=0;
    int i=0,line=1;
    int count,result,errorno=0;
 char array[30];
    char *word;
 printf("/n please input the file scanner name:");
    scanf("%s",filename);
    err=1;
    infile.open(filename,ios::nocreate|ios::in);
    while(! infile)
    {
        cout<<"cannot open file"<<endl;
        printf("please input  the file  name again:/n");
  scanf("%s",filename);
        infile.open(filename,ios::nocreate|ios::in);
        err++;
  if(err==3)
  {cout<<"SORROY YOU CAN'T VUEW THE PRGARME/n";
        cout<<"TANKE YOU VIEW"<<endl; 
  exit(0);}
    }
    infile.get(ch);
    while(ch!=EOF)
    {                 /*按字符依次扫描源程序,直至结束*/
        i=0;
        if(((ch>='A')&&(ch<='Z'))||((ch>='a')&&(ch<='z'))||(ch=='_'))
        {           /*以字母开头*/
            while(((ch>='A')&&(ch<='Z'))||((ch>='a')&&(ch<='z'))||(ch=='_')||((ch>='0')&&(ch<='9')))
            {
                array[i++]=ch;
                infile.get(ch);
            }
            word=new char[i+1];
   memcpy(word,array,i);
   word[i]='/0';
            intdeal(word);
            if(ch!=EOF)
    infile.seekg(-1,ios::cur);
        }
        else if(ch>='0'&&ch<='9')
        {          /*以数字开头*/
            while(ch>='0'&&ch<='9')
            {
                array[i++]=ch;
                infile.get(ch);
            }
            word=new char[i+1];
   memcpy(word,array,i);
   word[i]='/0';
            intdeal(word);
            if(ch!=EOF)
    infile.seekg(-1,ios::cur);
        }
        else if((ch==' ')||(ch=='/t'))
   ;           /*消除空格符和水平制表符*/
  else if(ch=='/n')
   line++;           /*消除回车并记录行数*/
  else if(ch=='/')
        {                 /*消除注释*/
   infile.get(ch);
   if(ch=='=')
   {              /*判断是否为‘/=’符号*/
    outfile.open("output.txt",ios::noreplace|ios::app);
    outfile<<"/=/t/t/t4/t/t/t32/n";
                outfile.close();
   }
   else if(ch!='*')
            {              /*若为除号,写入输出文件*/
                outfile.open("output.txt",ios::noreplace|ios::app);
    outfile<<"//t/t/t4/t/t/t13/n";
                outfile.close();
    outfile.seekg(-1,ios::cur);
   }
   else if(ch=='*')
   {              /*若为注释的开始,消除包含在里面的所有字符*/
    count=0;
   infile.get(ch);
    while(count!=2)
                {          /*当扫描到‘*’且紧接着下一个字符为‘/’才是注释的结束*/
     count=0;
     while(ch!='*')
      infile.get(ch);
     count++;
      infile.get(ch);
     if(ch=='/')
      count++;
     else
      infile.get(ch);
    }
   }
  }
  else if(ch=='"')
  {                 /*消除包含在双引号中的字符串常量*/
   outfile.open("output.txt",ios::noreplace|ios::app);
      outfile<<ch<<"/t/t/t4/t/t/t37/n";
   outfile.close();
   while(ch!='"')
   infile.get(ch);
            infile<<ch<<"/t/t/t4/t/t/t37/n";
   infile.close();
  }
  else
        {         /*首字符为其它字符,即运算限界符或非法字符*/
            array[0]=ch;
            infile.get(ch);       /*再读入下一个字符,判断是否为双字符运算、限界符*/
            if(ch!=EOF)
            {           /*若该字符非文件结束符*/
                array[1]=ch;
    word=new char[3];
    memcpy(word,array,2);
    word[2]='/0';
                result=search(word,4,1);      /*先检索是否为双字符运算、限界符*/
    if(result==0)
    {                           /*若不是*/
                    word=new char[2];
     memcpy(word,array,1);
     word[1]='/0';
     result=search(word,4,1);      /*检索是否为单字符运算、限界符*/
     if(result==0)
                    {                           /*若还不是,则为非法字符*/
      errordeal(array[0],line);
      errorno++;
      infile.seekg(-1,ios::cur);
                    }
                    else
     {     /*若为单字符运算、限界符,写入输出文件并将扫描文件指针回退一个字符*/
      outfile.open("output.txt",ios::noreplace|ios::app);
      outfile<<word<<"/t/t/t4/t/t/t"<<result<<"/t"<<endl;
      outfile.close();
      infile.seekg(-1,ios::cur);
     }
    }
                else
    {             /*若为双字符运算、限界符,写入输出文件*/
     outfile.open("output.txt",ios::noreplace|ios::app);
        outfile<<word<<"/t/t/t4/t/t/t"<<result<<endl;;
     outfile.close( );
    }
            }
            else
   {               /*若读入的下一个字符为文件结束符*/
    word=new char[2];
    memcpy(word,array,1);
    word[1]='/0';
    result=search(word,4,1);       /*只考虑是否为单字符运算、限界符*/
    if(result==0)                /*若不是,转出错处理*/
     errordeal(array[0],line);
    else
    {                            /*若是,写输出文件*/
     outfile.open("output.txt",ios::noreplace|ios::app);
        outfile<<word<<"/t/t/t4/t/t/t"<<result<<"/t"<<endl;
     outfile.close();
    }
   }
        }
        infile.get(ch);
    }
    infile.close();
cout<<"/nThere are "<<errorno<<" error(s)./n";         /*报告错误字符个数*/
}
void main()
{   char yn;
 
 do{
    init(); /*初始化*/
    scanner();/*扫描源程序*/

 printf("Are You continue(y/n)/n"); //判断是否继续?
 yn=getch();
 }while(yn=='y'||yn=='Y');
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
实验一:词法分析程序 一、实验目的     通过设计编制调试一个具体的词法分析程序,加深对词法分析原理的理解。并掌握在对程序设计语言源程序进行扫描过程中将其分解为各类单词的词法分析方法。 编制一个读单词过程,从输入的源程序中,识别出各个具有独立意义的单词,即基本保留字、标识符、常数、运算符、分隔符五大类。并依次输出各个单词的类型码及单词符号的自身值。(遇到错误时可显示“Error”,然后跳过错误部分继续显示) 二、实验要求 用C或C++写一个简单的词法分析程序,程序可以满足下列要求: 1、能分析如下几种简单的语言词法 (1) 标识符: ID=letter(letter|digit)* (2) 关键字(全部小写) main int float double char if then else switch case break continue while do for (3)整型常量:NUM=digit digit* (4)运算符 = + - * / < <= == != > >= ; ( )? : (5)空格由空白、制表符和换行符组成,用以分隔ID、NUM、运算符等,字符分析时被忽略。 2、单词符号和相应的类别码 假定单词符号和相应的类别码如下: 单词符号 种别码 int 1 = 17 float 2 < 20 if 3 <= 21 switch 4 == 22 while 5 != 23 Do 6 > 24 标识符 10 >= 25 整型常量 11 ; 26 + 13 ( 27 - 14 ) 28 * 15 ? 29 / 16 : 30 3、词法分析程序实现的功能 输入:单词序列(以文件形式提供),输出识别的单词的二元组序列到文件和屏幕 输出:二元组构成: (syn,token或sum) 其中: syn 为单词的种别码 token 为存放的单词自身符号串 sum 为整型常数 例: 源程序: int ab; float ef=20; ab=10+ef; 输出: (保留字--1,int) (标识符--10,ab) (分号--26,;) (保留字--2,float) (标识符--10,ef) (等号--17,=) (整数--11,20) (分号--26,;) (标识符--10,ab) (等号--17,=) (整数--11,10) (加号--13,+) (标识符--10,ef) (分号--26,;) 4、自己准备测试数据存放于TestData.txt文件中,测试数据中应覆盖有以上5种数据,测试结果要求以原数据与结果对照的形式输出并保存在Result.txt中,同时要把结果输出到屏幕。 5、提前准备 ① 实验前,先编制好程序,上机时输入并调试程序。 准备好多组测试数据(存放于文件TestData.txt中)。 6、写出实验报告 报告格式:要求有实验名称、实验目的、实验要求、实验内容、实验小结。 其中实验内容包括算法分析、程序流程图及程序代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值