/
chap4.c
109 lines (94 loc) · 1.42 KB
/
chap4.c
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
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
void parse_F();
void parse_T();
void parse_E();
void error(char *want, char got);
int i;
char *str = 0;
void error(char *want, char got)
{
fprintf(stderr, "Compling this expression:\n%s\n", str);
int j = i;
while (j--)
fprintf(stderr, " ");
fprintf(stderr, "^\n");
fprintf(stderr, "Syntax error at position: %d\n"
"\texpecting: %s\n"
"\tbut got : %c\n",
i, want, got);
exit(0);
return;
}
void parse_F()
{
char c = str[i];
if (isdigit(c)){
i++;
return;
}
if (c == '('){
i++;
parse_E();
c = str[i];
if (c == ')'){
i++;
return;
}
error("\')\'", c);
return;
}
error("\'0-9\' or \'(\'", c);
return;
}
void parse_T()
{
parse_F();
char c = str[i];
while (c == '*' || c == '/'){
i++;
parse_F();
c = str[i];
}
return;
}
void parse_E()
{
parse_T();
char c = str[i];
while (c == '+' || c == '-'){
i++;
parse_T();
c = str[i];
}
return;
}
void parse(char *e)
{
str = e;
i = 0;
parse_E();
if (str[i] == '\0')
return;
error("\'+\' or '\\0\'", str[i]);
return;
}
int main(char argc, char **argv)
{
// There are the following rules on an expression:
// 1. Every expression is represented as a string;
// 2. integers are non-negative;
// 3. integers are between 0-9.
char *e;
e = "(2)";
parse(e);
e = "(3+4*5))";
parse(e);
e = "(8-2)*3";
parse(e);
e = "(8-2)/3";
parse(e);
system("pause");
return 0;
}