C语言词法分析器(C++语言实现)
这是老师布置的编译原理的实验课任务,课余时间花了近一个星期的时间去编写代码(主要是C++太久没有用了,好多函数都不熟悉,查阅了很多资料),这次的词法分析也没有语法错误判断功能,如果想要增加功能可以在相关函数代码段增加即可.对于此法单元的种别码也只是简单区分,不过自己加上去就可以了
c语言词法分析流程如图所示:
代码如下:这次的代码算是我对代码整洁之道前期知识的一个练习,特别是变量的命名以及函数的编写,如果觉得写的不错可以看看我关于代码整洁之道的相关文章
这次的代码基本没有写注释,但是我相信大家结合流程图也能看懂,如果觉得太长可以将代码复制到visual studio中将函数代码块闭合起来这样看起来就逻辑清楚了
#include <iostream>
#include <string>
#include <map>
#include <ctype.h>
#include <algorithm>
using namespace std;
string readFile(string fileName);
string fileFilter();
string singleLineCommentsFilter();
string multilineCommmentsFileter();
string specialCharacterFilter();
void separateAndJudge();
bool isReservedWord(string vocabulary);
void separateAndJudge();
void showTokenData();
int digitStarted(int cnt);
bool isBoundSymbol(char ch);
bool isOperator(char ch);
int judgeStartingCharactorType(char ch);
bool isDigit(char ch);
bool isAlpha(char ch);
int alphaStarted(int cnt);
int underlineStarted(int cnt);
string transCharToString(char ch);
string codeSource;
map<string, int> tokens;//identifier is 1,reservedWord 2,digit 3,borderSymbol 4,operator 5
int main()
{
codeSource = readFile("h:\\testCode.txt");
cout << "This is source code" << endl << "---------------------------------" << endl << endl;
cout << codeSource << endl;
cout << "This is code filtered" << endl << "---------------------------------" << endl ;
codeSource = fileFilter();
codeSource = fileFilter();
cout << codeSource << endl;
separateAndJudge();
cout << "this is tokens " << endl;
showTokenData();
return 0;
}
string readFile(string fileName)
{
FILE* fp;
if ((fp = fopen(fileName.c_str(), "r")) == NULL)
{
cout << "cant open file";
exit(0);
}
else
{
string codeSource;
char ch;
while ((ch = fgetc(fp)) != EOF)
<