文档介绍:本代码只供学习参考:
词法分析源代码:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
string key[8]={"do","end","for","if","printf","scanf","then","while"};
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(),()))
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(),()))
return true ;
return false;
}
//分界符判断函数
bool IsSeparator(string ss) {
int i;
for(i=0;i<6;i++)
if(!strcmp(separator[i].c_str(),()))
return true;
return false;
}
void analyse(ifstream &in) {
string st="";
char ch;
int line=1,row=0;
while(((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;
(ch);
}
(-1,ios::cur);//文件指针(光标)后退一个字节
if(IsKey(st)) //判断是否为关键字查询关键字表;
cout<<st<<"\t("<<st<<","<<1<<")"<<'\t'<<'\t'<<"关键字"<<'\t'<<"("<<line<<","<<row<<")"<<endl;
else //否则为标示符
cout<<st<<"\t("<<st<<","<<2<<")"<<'\t'<<'\t'<<"标识符"<<'\t'<<"("<<line<<","<<row<<")"<<endl;
}
else
if(IsDigit(ch)) //无符号整数处理
{
row++;
while(IsDigit(ch))
{st+=ch;
ch=();
}
(-1,ios::cur);
cout<<st<<"\t("<<st<<","<<3<<")"<<'\t'<<'\t'<<"常数"<<'\t'<<"("<<line<<","<<row<<")"<<endl;
// break;
}
else
{st="";
st+=ch;
if