这学期学习编译原理,第一个实验就是做一个简易的词法分析器。
自己写了一个,保存在这。以后需要的时候再来看看。
// 对于每一行输出的解释:
// 1.第一个为取出来的单词
// 2.第二个为该单词首字母出现的位置 [行: 列]
// 3.第三个为该单词的种类码:
// -1 错误
// 1 关键字
// 2 自定义标识码
// 3 数字
// 4 常用符号
// 5 运算符
// 6.比较或赋值符号
//
//
//
//
//
#include <cstdio>
#include <algorithm>
#include <queue> //队列
#include <ctype.h>
#include<cstdlib>
using namespace std;
typedef struct word //单词结构体
{
int row; //行
int column; //列
int category; //种别码
char str[0];
}word;
queue<word*> words; // 单词队列
//关键字
const char* keys[] = { "if","else","for","while","do","return","break","continue","int","double","char","main" };
//常用符号
const char* border[] = { ",",";","{","}","(",")","[","]","&" };
//运算符
const char* arithmetic[] = { "+","-","*","/","%" };
//比较符
const char* relation[] = { "<","<=","=","==","!=",">=",">" };
// 单词转结构体
word* res_struct(int row, int column, int category, char* str, int n);
// 词法分析器
int lexical_analyzer(FILE* fp);
// 单词种类判断
int word_estimate(char* str, int n, int key, int row, int column);
int main()
{
FILE* fp = NULL;
word *aword;
if ((fp = fopen("1.txt", "r"))== NULL)
{
printf("打不开文件\n");
return -1;
}
lexical_analyzer(fp); //词法分析
while