-
Notifications
You must be signed in to change notification settings - Fork 1
/
Parser.cpp
62 lines (53 loc) · 1.09 KB
/
Parser.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
#include <iostream>
#include <stdio.h>
using namespace std;
class Parser {
public:
void expr();
void term();
void match(int);
Parser() ;
static int lookahead;
};
int Parser::lookahead = 0; //static need init
Parser::Parser() { Parser::lookahead = getchar(); }
void Parser::expr()
{
term();
while(true) {
if(Parser::lookahead == '+') {
match('+');
term();
cout << '+';
} else if(Parser::lookahead == '-') {
match('-');
term();
cout << '-';
}
else return;
}
}
void Parser::term()
{
if( '0' <= (char)Parser::lookahead && (char)Parser::lookahead <= '9') {
cout << (char)Parser::lookahead;
match(Parser::lookahead);
}
// else syntax error
}
void Parser::match(int t)
{
if( Parser::lookahead == t ) Parser::lookahead = getchar();
// else syntax error
}
int main()
{
Parser* parse = new Parser();
try {
parse->expr();
} catch (char* e) {
cout << endl;
cout << e << endl;
}
cout << '\n' << endl;
}