一、原创性声明
本实验代码全部为自己编写。
二、实验要求
1. 手工构造一个简单的词法分析程序。
- 能够识别标识符、整数、关键字、算符、界符
- 可输出至文件,也可输出至屏幕
三、完成情况
- 功能1 : 能够识别标识符、整数、关键字、算符、界符、可输出至屏幕
² 功能描述: 能够识别关键字、算符、界符、标识符、算符
² 完成情况: 已经完成
² Bug:
² 备注:本程序中只是把"if","int","include","cout","float","else","main","return"作为关键字
l 功能2 : 选做内容
功能描述: 根据状态转换图手工构造词法分析程序。从以下方法中选一:
² 直接转向法
² 表驱动法
² 完成情况:
四、实现方案
读取文件中的内容,将单词单独隔离出来分析是不是关键字,如果是关键字那么就不是标识符,否则判断是不是标识符,界符和算符可以设置一个数组存放拥有的界符和算符,将文件中的内容与之对应看是界符还是算符。
五、创新和亮点
读取文件获取文件的内容模仿编译器的识别。
六、运行结果
注:本程序中把"if","int","include","cout","float","else","main","return"作为了关键字
读取的文件:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int i=36;
cout<<"请输入您的句子:"<<endl;
cin>>str;
cout<<str<<endl;
return 0;
}
源代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string guanJianZi[]={"if","int","include","cout","float","else","main","return"};
int guanJianZiNum=8;//记录上面的数组里面有几个关键字方便下面的程序使用
//{"this","include","int","float","if","else","return"};
char suanFu[]={'+','-','*','/','='};
int suanFuNum=5;//记录上面的数组里面有几个算符方便下面的程序使用
char jieFu[]={ ';' , '{' , '}' , '[' , ']' };
int jieFuNum=5;//记录上面的数组里面有几个界符方便下面的程序使用
//记录是不是关键字如果为1就是关键字如果为0的话就不是关键字方便于关键字和标识符做区分
int flag=0;
//判断标识符
int isBiaoZhiFu(string word,int flag)
{
int count=0;
if(flag==0)
{
for(int i=0;i<word.length();i++)
{
if((word[i]>='a'&&word[i]<='z') || (word[i]>='A'&&word[i]<='Z') || (word[i]>='0'&&word[i]<='9'&&(word[0]>='a'&&word[0]<='z')||(word[0]>='A'&&word[0]<='Z')) ||word[i]=='_')//字母数字下划线组成并且第一个必须是字母或者下划线组成的
{
cout<<"标识符:"<<word<<endl;
break;
}
}
}
return flag;
}
//判断关键字,这个地方要用flag使得关键字和标识符区分开
int isGuanJianZi(string word,int flag)
{
if(flag==0)
{
for(int i=0;i<guanJianZiNum;i++)
{
if(word==guanJianZi[i])
{
cout<<"关键字:"<<word<<endl;
flag=1;
}
}
}
return flag;
}
//算符的判断
void isSuanFu(string word)
{
for(int j=0;j<suanFuNum;j++)
{
for(int i=0;i<word.length();i++)
{
if(word[i]==suanFu[j])
{
cout<<"算符:"<<word[i]<<endl;
break;
}
}
}
}
//界符的判断
void isJieFu(string word)
{
for(int i=0;i<word.length();i++)
{
for(int j=0;j<jieFuNum;j++)
{
if(word[i]==jieFu[j])
{
cout<<"界符:"<<word[i]<<endl;
break;
}
}
}
}
void isInt(string word)
{
for(int j=0;j<word.length();j++)
{
if(word[j]>='0'&&word[j]<='9')
{
cout<<"整数:"<<word<<endl;
break;
}
}
}
int main()
{
//cout<<sizeof(guanJianZi)<<endl;
char ch;
string complWord="";
string complWord2="";
//文件流:输入的方式读取文件
ifstream infile("bianYi.txt",ios::in);
if(!infile)
{
cerr<<"读取文件出错了!"<<endl;
exit(1);
}
while(infile.get(ch))//从文件读取字符进来
{
//cout<<ch<<endl;
if(ch!=' '&&ch!='\n')
complWord2+=ch;
if(ch!=' '&&ch!='\n'&&ch!='\t'&&ch!='+'&&ch!='-'&&ch!='*'&&ch!='/'&&ch!='='&&ch!=','&&ch!='{'&&ch!='}'&&ch!='['&&ch!=']'&&ch!='('&&ch!=')'&&ch!=';'&&ch!='<'&&ch!='>'&&ch!='#')//把整个的单词分离出来
{
complWord+=ch; //不是空格的话就说明是单词的一部分
}
else
{
//cout<<complWord<<endl;//输出检验
//先判断关键字再判断标识符
flag=isGuanJianZi(complWord,flag);
isBiaoZhiFu(complWord,flag);
isInt(complWord);
complWord="";
flag=0;
}
}
//cout<<complWord2<<endl;
isSuanFu(complWord2);
isJieFu(complWord2);
return 0;
}