词法分析器

#include <stdio.h> 
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
char ch=' ',strToken[20]={'\0'};
int k=0,flag;//该词法器可识别:字母数字串、数字串、基本符号(+-/*=<>;,)
void GetChar()
{
	ch=getchar();
}
void GetBC()
{
	while(ch==' ')
	{GetChar();flag=1;}
}
void Concat()
{
	strToken[k++]=ch;
}
int IsLetter()
{
	return isalpha(ch);
}
int IsDigit()
{
	return isdigit(ch);
}
int f=1;
void return1(int no,char s[])
{
	if(f==1)
	printf("输出:\n");f++;
	printf("     (%d,%s)\n",no,s);
	strToken[0]='\0';k=0;
}
void return2(int no,char c)
{
	if(f==1)
	printf("输出:\n");f++;
	printf("     (%d,%c)\n",no,c);
}
void scanner()
{
	if(IsLetter())
	{
		while(IsLetter()||IsDigit())
		{
			Concat();GetChar();
		}
		flag=1;strToken[k]='\0';
		return1(1,strToken);
	}
	else if(IsDigit())
	{
		while(IsDigit())
		{
			Concat();GetChar();
		}
		flag=1;strToken[k]='\0';
		return1(2,strToken);
	}
	else if(ch=='=')
	{
		int kk=1;
		while(ch=='='&&kk!=3)
		{
			Concat();GetChar();kk++;
		}
		flag=1;strToken[k]='\0';
		return1(3,strToken);
	}
	else if(ch=='+')
	{
		return2(11,'+');
	}
	else if(ch=='-')
	{
		return2(12,'-');
	}
	else if(ch=='*')
	{
		return2(13,'*');
	}
	else if(ch=='/')
	{
		return2(14,'/');
	}
	else if(ch=='<')
	{
		return2(15,'<');
	}
	else if(ch=='>')
	{
		return2(16,'>');
	}
	else if(ch=='(')
	{
		return2(17,'(');
	}
	else if(ch==')')
	{
		return2(18,')');
	}
	else if(ch==':')
	{
		return2(19,':');
	}
	else if(ch==';')
	{
		return2(20,';');
	}
	else if(ch==',')
	{
		return2(21,',');
	}
	else if(ch==' ')
		GetBC();
	else exit(0); 
}
void main()
{
	printf("输入:");
	GetChar();GetBC();
	while(ch)
	{
		flag=0;
		scanner();
		GetBC();	
		if(flag==0)	GetChar();//flag为1时,不执行GetChar()
	}
	scanf("%d");
}

运行:

输入:if(i>100) then i=0
输出:
     (1,if)
     (17,()
     (1,i)
     (16,>)
     (2,100)
     (18,))
     (1,then)
     (1,i)
     (3,=)
     (2,0)
Press any key to continue

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

todaycode

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值