📄 pascal.cpp
字号:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h> /*用到判断字符的函数*/
#include<string.h> /*复制字符串用*/
/********************************************************
* 定义数据结构 (使用全局变量记录) *
*********************************************************/
char ch; /* 当前处理字符 */
char *keywords[]={"program","procedure","begin","end","while","do"}; /* 关键字 */
char *jF[]={"+","*",":",":=","=",",",";"}; /* 界符 */
typedef struct{
int id; /* 存放id */
char value[20]; /* 存放字符串 */
}TokenType;
TokenType Token[40]; /* 定义一个全局变量存放token序列 */
int tk=0; /* 记号序列 */
int line=1; /* 记录行号 */
void error() /* 错误信息输出 */
{
printf("ERROR In Line %d\n",line); /* 错误出现在哪行中 */
return;
}
void display() /* 显示token序列 */
{
int i;
printf("========================\n");
for(i=0;i<tk;i++)
{
printf("--[%d]\t%s\t%d\n",i+1,Token[i].value,Token[i].id);
}
return;
}
void lexidkey() /* 判断id和关键字 */
{
char str[20]={"\0"}; /* 初始化为空 */
int i,j;
str[0]=ch;
ch=getchar();
for(i=1;isalpha(ch);i++) /* 判断是否都是字母,存放在str 中 */
{
str[i]=ch;
ch=getchar();
}
for(j=0;j<6;j++) /* 关键字判断 */
{
if(strcmp(str,keywords[j])==0)
{
Token[tk].id=j+3;
strcpy(Token[tk].value,str);
tk++;
return;
}
}
for(;isalnum(ch);i++) /* 序列之中是否含有数字 */
{
str[i]=ch;
ch=getchar();
}
Token[tk].id=1; /* 标识符确定 */
strcpy(Token[tk].value,str);
tk++;
return;
}
void lexflag() /* 判断是否是界符 */
{
char str[2]={"\0"};
int i;
str[0]=ch;
ch=getchar();
for(i=0;i<7;i++) /* 单个界符判断 */
{
if(strcmp(str,jF[i])==0)
{
Token[tk].id=i+9;
strcpy(Token[tk].value,str);
tk++;
return;
}
}
str[1]=ch;
ch=getchar();
for(i=0;i<7;i++) /* 双个界符判断 */
{
if(strcmp(str,jF[i])==0)
{
Token[tk].id=i+9;
strcpy(Token[tk].value,str);
tk++;
return;
}
}
return;
}
void lexconst() /* 常数判断 */
{
char str[20]={"\0"};
int i;
str[0]=ch;
ch=getchar();
for(i=1;isdigit(ch);i++) /* 识别常数并记录在数组中 */
{
str[i]=ch;
ch=getchar();
}
Token[tk].id=2; /* 确定token 常数序列 */
strcpy(Token[tk].value,str);
tk++;
return;
}
int isjf(char ch) /* 判断是否是界符开始字段 */
{
switch(ch)
{
case '+':
case '*':
case ':':
case '=':
case ',':
case ';':
return 1;
default:
return 0;
}
}
int first(char ch) /* 判断首先使用哪个判别函数 */
{
if(isalpha(ch)) /* 避免在主函数中条件判断过多,层次杂乱 */
return 1;
else if(isdigit(ch))
return 2;
else if(isjf(ch))
return 3;
else return 0;
}
/*********************************************
* 主函数 *
*********************************************/
int main()
{
ch=getchar(); /* 超前扫描字符 */
while(1)
{
if(ch=='@') /* 程序结束标志 '@' */
break;
if(ch==' '||ch=='\t') /* 删除空格和tab */
{
ch=getchar();
continue;
}
if(ch=='\n') /* 行号记录 */
{
ch=getchar();
line++;
continue;
}
switch(first(ch)) /* 判断选用哪个函数进行判别token 序列 */
{
case 1:lexidkey();break;
case 2:lexconst();break;
case 3:lexflag();break;
default:error();exit(0); /* 错误返回 */
}
}
display(); /* 显示token序列 */
system("pause"); /* 调用dos暂停,用于显示 */
system("pause");
return 1; /* 成功结束 */
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -