发布时间 : 星期一 文章编译原理实验词法分析语法分析更新完毕开始阅读364fbfe6ba0d4a7302763ab7
本代码只供学习参考: 词法分析源代码: #include
string key[8]={\string optr[4]={\
string separator[6]={\char ch;
//判断是否为保留字 bool IsKey(string ss) { int i; for(i=0;i<8;i++)
if(!strcmp(key[i].c_str(),ss.c_str())) return true; return false; }
//字母判断函数
bool IsLetter(char c) { if(((c>='a')&&(c<='z'))||((c>='A')&&(c<='Z'))) return true; return false; }
//数字判断函数
bool IsDigit(char c) { if(c>='0'&&c<='9') return true; return false; }
//运算符判断函数
bool IsOptr(string ss) { int i; for(i=0;i<4;i++)
if(!strcmp(optr[i].c_str(),ss.c_str())) return true ; return false; }
//分界符判断函数
bool IsSeparator(string ss) { int i; for(i=0;i<6;i++)
if(!strcmp(separator[i].c_str(),ss.c_str()))
return true; return false; }
void analyse(ifstream &in) { string st=\ char ch; int line=1,row=0; while((in.get(ch))) { st=\ if((ch==' ')||(ch=='\\t')){} //空格,tab健 else if(ch=='\\n') {line++;row=0; } //换行行数加一处理 else if(IsLetter(ch)) //关键字、标识符的处理 {
row++; while(IsLetter(ch)||IsDigit(ch)) {
st+=ch; in.get(ch); } in.seekg(-1,ios::cur);//文件指针(光标)后退一个字节 if(IsKey(st)) //判断是否为关键字 查询关键字表; cout< cout< else if(IsDigit(ch)) //无符号整数处理 { row++; while(IsDigit(ch)) {st+=ch; ch=in.get(); } in.seekg(-1,ios::cur); cout< 关键标识常字 符 数 // break; } else {st=\ st+=ch; if(IsOptr(st)) //运算符处理 { row++; cout< } else if(IsSeparator(st))//分隔符处理 { row++; cout< else{ switch(ch){row++; case'=' : {row++;cout<<\关系运算符\ case'>' :{row++;ch=in.get(); if(ch=='=') cout<<\关系运算符\ else {cout<<\关系运算符\ in.seekg(-1,ios::cur);} } break; case'<' :{row++;ch=in.get(); if(ch=='=')cout<<\关系运算符\ else if(ch=='>') cout<<\关系运算符\ else{cout<<\关系运算符\ in.seekg(-1,ios::cur);} }break; default :{row++; cout< \ } }} } } int main() { ifstream in; in.open(\ cout<<\关键字-》1 标识符-》2 常数-》3 运算符-》4 分隔符-》5\ if(in.is_open()) { analyse(in); in.close(); system(\ } else cout<<\文件操作出错\ } 语法分析实验源代码LL #include const int MaxLen=20; //初始化栈的长度 const int Length=20;//初始化数组长度 char Vn[5]={'E','G','T','S','F'};//非终结符数组 char Vt[8]={'i','(',')','+','-','*','/','#'};//终结符数组 char ch,X;//ch读当前字符,X获取栈顶元素 char strToken[Length];//存储规约表达式 struct LL//ll(1)分析表的构造字初始化 { char*c; }; LL E[8]={\LL G[8]={\LL T[8]={\LL S[8]={\LL F[8]={\ class stack//栈的构造及初始化