编译原理 —— C语言词法分析程序(C++实现)

本文介绍了如何使用C++来实现C语言的词法分析程序,通过解析测试文件,展示了词法分析过程。内容包括源代码的组织结构,如lex.h、lex.cpp和main.cpp等关键文件的职责。
摘要由CSDN通过智能技术生成

测试文件:
在这里插入图片描述

运行结果:
在这里插入图片描述
单词种别码表:
在这里插入图片描述


源代码

lex.h

#ifndef LEX_H_INCLUDED
#define LEX_H_INCLUDED

#include <iostream>
#include <ctype.h>
#include <string>
#include <cstdio>
#include <stdlib.h>
using namespace std;

typedef struct  /* 单词二元组的结构 */
{
   
    int typenum;    /* 种别码 */
    string token;    /* 自身字符串 */
} WORD;


WORD* scaner(FILE *fp); // 对文件扫描读取
int keyOrIdentifier(string token);  // 判断是关键字还是标识符
#endif // LEX_H_INCLUDED

lex.cpp

#include "lex.h"

#define _KEY_WORD_END "waiting for your expanding"  /* 定义关键字结束标志 */
string KEY_WORDS[]= {
   "main","return","if","else","for","include","printf","int","char",_KEY_WORD_END};   /*可扩充的关键字词组*/
int line_num=1;
/* 判断是标识符还是关键字*/
int keyOrIdentifier(string token)
{
   
    int i=0;
    while(KEY_WORDS[i]!=_KEY_WORD_END)
    {
   
        if(KEY_WORDS[i]==token)
        {
   
            return i+1;
        }
        i=i+1;
    }
    return 10;
}

WORD* scaner(FILE *fp)
{
   
    char ch;
    string token="";
    WORD* myword=new WORD;
    myword->typenum=0;
    myword->token="";

    ch=fgetc(fp);

    /* 判断回车 */
    if(int(ch)==10)
    {
   
        line_num++;
        return (myword);
    }
    /* 判断空格 */
    else if(isspace(ch))
    {
   
        return (myword);
    }
    /* 标识符及关键字 */
    else if(isalpha(ch))    //如果首字符是字母
    {
   
        while(isalpha(ch
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值