编译原理词法分析
- 格式:docx
- 大小:14.37 KB
- 文档页数:5
上机练习一:词法分析一个PASCAL语言子集(PL/0)词法分析器的设计与实现1.按照P45的算法思想,使用循环分支方法实现PL/0语言的词法分析器,该词法分析器能够读入使用PL/0语言书写的源程序,输出单词符号串及其属性到一中间文件中,具有一定的错误处理能力,给出词法错误提示。
2.源代码#include<iostream>#include<fstream>#include<string>using namespace std;#define MAX 1000string key[15] = { "begin", "end", "if", "then", "else", "while", "write", "read","do", "call", "const", "var", "procedure", "program", "odd" };//保留字int IsLetter(char c ) //判断字母{if (((c <= 'z')&&(c >= 'a')) || ((c <= 'Z')&&(c >= 'A')))return 1;else return 0;}int IsDigit(char c) //判断数字{if ((c >= '0')&&(c <= '9'))return 1;else return 0;}int IsKey(string strToken) //判断保留字{int i;for (i = 0; i<15; i++){if (key[i].compare(strToken) == 0)return i;}return 15;}string Concat(char ch,string strToken){strToken += ch;return strToken;}int main(){ifstream file;int r=0;char ch;int l=0;int ID;//保留字的idstring strToken="";file.open ("1.txt");//打开第i个记事本if(!file)cout<<"打开文件失败!";ch=file.get();while(!file.eof()){//if (ch == ' ' || ch == '\t' || ch == '\n') //滤掉空白字符//while( ch == '\n')//l ++;if (ch == ' ' || ch == '\t')ch=file.get();while (ch == '\n'){l ++;ch = file.get();}if(IsLetter(ch)){strToken = ""; //每次都需要对strToken置空串处理while(IsLetter(ch)||IsDigit(ch)){strToken = Concat(ch,strToken);ch = file.get();}ID=IsKey(strToken);if(ID < 15){cout<< "保留字为:"<< strToken<< endl;}if(ID == 15){cout<< "标识符为:"<< strToken<< endl;}}if(IsDigit(ch)){strToken = ""; //每次都需要对strToken置空串处理while(IsDigit(ch)){strToken = Concat(ch,strToken);ch = file.get();}if(IsLetter(ch)) //数字后面跟字母,错误词法{while(IsLetter(ch)||IsDigit(ch)){strToken = Concat(ch,strToken);ch = file.get();}cout <<"词法错误!(数字后面跟字母) "<< strToken<< endl;}elsecout<<"数字为:"<<strToken<<endl;}else switch (ch){case '+':{cout <<"标识符为:\n" <<"+" <<endl;ch=file.get();break;} case '-':{cout <<"标识符为:\n" <<"-" <<endl;ch=file.get();break;} case '*':{cout <<"标识符为:\n" <<"*" <<endl;ch=file.get();break;}case '/':{cout <<"标识符为:\n" <<"/" <<endl;ch=file.get();break;} case '>':{ch = file.get();if(ch == '=')cout <<"标识符为:\n" <<">="<<endl;elsecout <<"标识符为:\n" <<">"<<endl;ch=file.get();break;}case '<':{ch = file.get();if(ch == '>')cout <<"标识符为:\n" <<"<>" <<endl;else if(ch = '=')cout <<"标识符为:\n" <<"<=" <<endl;elsecout <<"标识符为:\n" <<"<" <<endl;ch=file.get();break;}case '=':{cout<< "标识符为:\n" <<"=" <<endl; ch=file.get();break;}case':':{ch = file.get();if(ch == '='){cout<< "界符为:"<< ":="<<endl;}else cout<< "词法错误!(‘:’后面没有‘=’)"<< endl;ch=file.get();break;}case ';':{cout <<"界符为:" <<";" <<endl;ch=file.get();break;}case ',':{cout <<"界符为:" <<"," <<endl;ch=file.get();break;}case '(':{cout <<"界符为:" <<"(" <<endl;ch=file.get();break;}case ')':{cout <<"界符为:" <<")" <<endl;ch=file.get();break;}}}printf("%d",l);return 0;}。