词法分析器C++读取外部txt(编译原理)
词法分析器的参考文章:
https://blog.youkuaiyun.com/qq_32623363/article/details/79911321)
在原文章的基础上,我加入了关键字的识别,并将词法分析器设计为一个独立的程序,从文件中读取源程序,将其变换成相应的符号序列;
c++读取txt文件的参考文章https://blog.youkuaiyun.com/m0_38033475/article/details/94394087
#include <iostream>
#include <string>
#include<fstream>
using namespace std;
#define MAX_LEN 200
//将一个字符串内容清空
void clearArray(char *c)
{
int len = strlen(c);
for(int i = 0; i < len; i++)
{
c[i] = '\0';
}
}
//判断是否为数字,true为是,false为不是
bool isDigit(char c){
if(c >= '0' && c <= '9')
{
return true;
}
else
{
return false;
}
}
//判断是否为字母,ture为是,false为不是
bool isChar(char c)
{
if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') )
{
return true;
}
else
{
return false;
}
}
/*
* 单词输出函数
* 该单词的意义
* 经过词法分析器分析后得到的单个单词
*/
void print(string label, char *word)
{
ofstream outfile("output.txt",ios::app);
outfile << label << ": " << word << endl;
}
/*
* 词法分析函数
* 输入字符串指针
* 该函数对输入串进行分析,并分割成单词后输出
*/
void analysis(char* inChar)
{
//用于对词法分析后的单词进行保存
char tempChar[MAX_LEN] = {
0};
// 作为tempChar的一个索引
int j = 0;
//用于遍历inChar字符数组
int i = 0;
while(inChar[i] != '\0')
{
switch(inChar[i])
{
case '-':
tempChar[j++] = inChar[i];
print("减号",tempChar);
j = 0;
clearArray(tempChar);
break;
case '=':
tempChar[j++] = inChar[i