-
Notifications
You must be signed in to change notification settings - Fork 6
/
1 词法分析器.cpp
138 lines (134 loc) · 2.7 KB
/
1 词法分析器.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
char token[50];
char ch;
char *keyword[]={"if","else","while","for","int","float"};
char program[100];
int current=0,q=0;int row=1,sign;
int number=0;
void run(){
sign=0;
number=0;
ch=program[current++];
q=0;
while(ch==' ')
{
ch=program[current++];
}
//字母开头(可能是标识符或者关键字)
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
{
q=0;
while((ch>='0'&&ch<='9')||(ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
{
token[q++]=ch;
ch=program[current++];
//含有数字,标识符
if((ch>='0'&&ch<='9'))
{
sign=1;
}
}
current--;
//不含数字,可能是关键字
if(sign!=1){
for(int i=0;i<6;i++)
{
if(strcmp(token,keyword[i])==0)
{
sign=i+3;
}
}
}
if(sign==0)
sign=1;
}else if((ch>='0'&&ch<='9'))
{
number=0;
while((ch>='0'&&ch<='9')){
number=number*10+ch-'0';
ch=program[current++];
}
current--;
sign=2;
if(number>65535)sign=-1;
}else switch(ch)
{
case '+':sign=35;token[q++]=ch;break;
case '-':sign=36;token[q++]=ch;break;
case '(':sign=55;token[q++]=ch;break;
case ')':sign=56;token[q++]=ch;break;
case ';':sign=57;token[q++]=ch;break;
case '=':
ch=program[current++];
if(ch=='='){
sign=38;token[q++]=ch;token[q++]=ch;
break;
}else{
sign=37;
token[q++]='=';
current--;
break;
}
case '<':
ch=program[current++];
if(ch=='='){
sign=40;token[q++]='<';token[q++]='=';
break;
}else{
sign=39;
token[q++]='<';
current--;
break;
}
case '>':
ch=program[current++];
if(ch=='=')
{
sign=42;
token[q++]='>';token[q++]='=';
break;
}else{
sign=41;
token[q++]='>';
current--;
break;
}
case '{':sign=58;token[q++]=ch;break;
case '}':sign=59;token[q++]=ch;break;
case ',':sign=60;token[q++]=ch;break;
case '\n':sign=-3;token[q++]=ch;break;
default:sign=-1;break;
}
token[q++]='\0';
}
int main()
{
FILE *fp;
if((fp=fopen("input.txt","r"))==NULL)
{
cout<<"ERROR"<<endl;
exit(1);
}
current=0;
while(EOF!=(ch=fgetc(fp))){
program[current++]=ch;
}
int total=current;
current=0;
while(current<total){
run();
switch(sign)
{
case 1:cout<<"("<<sign<<",指向"<<token<<"在符号表的入口)"<<endl;break;
case 2:cout<<"("<<sign<<",指向"<<number<<"在符号表的入口)"<<endl;break;
case -1:cout<<row<<"行输入"<<ch<<"错误"<<endl;break;
case -3:row++;break;
default:cout<<"("<<sign<<","<<'-'<<")"<<endl;break;
}
}
return 0;
}