9
9
#include < stdexcept>
10
10
#include < limits>
11
11
#include < string>
12
+ #include < unordered_set>
12
13
13
- enum TokenType { INTEGER, PLUS, END };
14
+ enum TokenType { INTEGER, PLUS, MINUS, END };
14
15
15
16
class Token {
16
17
friend std::ostream &operator <<(std::ostream &, const Token &);
@@ -38,8 +39,17 @@ class Interpreter {
38
39
39
40
inline void throwError () { throw std::runtime_error (" Error parsing input" ); }
40
41
42
+ // 跳过空格
43
+ void eatWhitespace () {
44
+ // 跳过符号开头部分的空格
45
+ while (_pos < _text.size () && _text[_pos] == ' ' ) {
46
+ ++_pos;
47
+ }
48
+ }
49
+
41
50
// 一个简单的词法分析器(lexer)
42
51
Token getNextToken () {
52
+ eatWhitespace ();
43
53
if (_pos >= _text.size ()) {
44
54
return Token (END);
45
55
}
@@ -54,15 +64,18 @@ class Interpreter {
54
64
} else if (_text[start_pos] == ' +' ) {
55
65
++_pos;
56
66
return Token (PLUS);
67
+ } else if (_text[start_pos] == ' -' ) {
68
+ ++_pos;
69
+ return Token (MINUS);
57
70
}
58
71
throwError ();
59
72
// should not be here
60
73
return Token (END);
61
74
}
62
75
63
76
// 确保当前 token 的 type 为指定的 token_type,并且获取下一个 token
64
- void eatToken (const TokenType &token_type ) {
65
- if (_current_token._type == token_type ) {
77
+ void eatToken (const std::unordered_set< TokenType> &types ) {
78
+ if (types. find ( _current_token._type ) != types. end () ) {
66
79
_current_token = getNextToken ();
67
80
return ;
68
81
}
@@ -77,22 +90,35 @@ class Interpreter {
77
90
_current_token = getNextToken ();
78
91
79
92
auto left = _current_token;
80
- eatToken (INTEGER);
93
+ #ifdef DEBUG
94
+ std::cout << " left: " << left << std::endl;
95
+ #endif
96
+ eatToken ({INTEGER});
81
97
82
98
auto op = _current_token;
83
- eatToken (PLUS);
99
+ #ifdef DEBUG
100
+ std::cout << " op: " << op << std::endl;
101
+ #endif
102
+ eatToken ({PLUS, MINUS});
84
103
85
104
auto right = _current_token;
86
- eatToken (INTEGER);
87
-
88
- return left._value + right._value ;
105
+ #ifdef DEBUG
106
+ std::cout << " right: " << right << std::endl;
107
+ #endif
108
+ eatToken ({INTEGER});
109
+ if (op._type == PLUS) {
110
+ return left._value + right._value ;
111
+ } else if (op._type == MINUS) {
112
+ return left._value - right._value ;
113
+ }
114
+ return std::numeric_limits<int >::infinity ();
89
115
}
90
116
};
91
117
92
118
int main () {
93
119
std::string text;
94
120
95
- while (std::cin >> text) {
121
+ while (getline ( std::cin, text) ) {
96
122
auto interpreter = Interpreter (text);
97
123
std::cout << interpreter.expr () << std::endl;
98
124
}
0 commit comments