⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 regoperator.cpp

📁 C语言词法分析器 实现简单的词法分析
💻 CPP
字号:

#include <windows.h>
#include "commendef.h"

static int  OPERATOR_NUM = 35;
static char OPERATOR[][5] =
{
	"+" ,"-" ,"*" ,"/" ,"%" , "=",             // 基本的算术运算符号(6个)		
	"+=","-=","*=","/=","%=","++","--",        // 高级算术运算符(7个)
	"<" ,">" ,"==","<=",">=","!=",             // 关系运算符(6个)
	"&" ,"|" , "^","~","&=" ,"|=","^=",	       // 位运算符(7个)
	"&&","||","!",                             // 逻辑运算符(3个)
	"<<","<<=",">>",">>=",                     // 位运算符(4个) 
	".","->",		                           // 成员选择运算符(2个)   	
};

static char VALID_OPERATOR_CHAR[] = "+-*/%=<>&|!~.^";

bool IsValidOperatorChar(char ch)
{
	int i,len;
	len = strlen(VALID_OPERATOR_CHAR);
	for(i = 0; i < len ; i++)
		if (ch == VALID_OPERATOR_CHAR[i]) return true;

	return false;
}

static bool IsOperator(const char *p)
{
	int i;		
	for(i = 0; i < OPERATOR_NUM; i++)
		if (strcmp(p,OPERATOR[i]) == 0) return true;
	return false;
}

static bool RecogniseRemark(char** pStr);

bool RecogniseOperator(char** pStr,RECOG_RESULT* pResult)
{
	char szOperator[5],*pInput,ch;
	int  len;

	pResult->Right = false;

	pInput = *pStr; 	ch = *pInput;
	if (ch == '/' && 
		(*(pInput + 1) == '*' || *(pInput + 1) == '/')	)
	{   // 识别注释
		pResult->Right    = RecogniseRemark(pStr);
		pResult->WordType = WORD_REMARK;
		return pResult->Right;
	}

	for(len = 3; len >= 1; len--)
	{
		ZeroMemory(szOperator,sizeof(char) * 5);
		CopyMemory(szOperator,*pStr,sizeof(char) * len);
		if (IsOperator(szOperator)) 
		{			
			pResult->WordType = WORD_OP;
			pResult->Right = true;
			CopyMemory(pResult->Value.Operator,*pStr,len);
			pResult->Value.Operator[len] = 0;
			*pStr += len;
			return true;
		}
	}
	return false;
}

// 识别注释
static bool RecogniseRemark(char** pStr)
{
	char       *pInput,ch,ch2;	
	
	pInput = *pStr; ch = *pInput;
	if (ch == '/') // 可能是注释
	{
		ch = *(pInput + 1);
		if (ch == '/') // 单行注释
		{
			while (*pInput && (ch = *pInput++) != NEWLINE);
			*pStr = pInput;
			return true;
		}
		else if (ch == '*') // 多行注释
		{
			pInput += 2;
			while (*pInput && *(pInput+1))
			{
				ch  = *pInput;
				ch2 = *(pInput + 1);
				if (ch == '*' && ch2 == '/') 
				{
					pInput += 2;
					*pStr = pInput;
					return true;
				}
				pInput++;
			}
			return false;  // 注释没有结束标记
		}
		else 
			return false;  // 不是注释
	}
	return false;
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -