-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsmInfixToPostFix.cpp
More file actions
90 lines (81 loc) · 2.09 KB
/
smInfixToPostFix.cpp
File metadata and controls
90 lines (81 loc) · 2.09 KB
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
#include <iostream>
#include <vector>
#include "smStackMAchine.hpp"
using namespace std;
class smToyCompiler {
void term();
void factor();
void expr();
void match(char);
void error();
char lookahead;
string input;
vector<string> output;
int pos;
char getchar() {
return input[pos++];
}
public:
smToyCompiler() {
pos = 0;
}
vector<string> compile(string in) {
input = in;
lookahead = getchar();
expr();
output.push_back("show");
return output;
}
};
void smToyCompiler::expr() {
term();
while (1) {
if (lookahead == '+') {
match('+'); term(); output.push_back("add");
} else if (lookahead == '-') {
match('-'); term(); output.push_back("sub");
} else break;
}
}
void smToyCompiler::term() {
factor();
while (1) {
if (lookahead == '*') {
match('*'); factor(); output.push_back("mult");
} else if (lookahead == '/') {
match('/'); factor(); output.push_back("div\n");
} else break;
}
}
void smToyCompiler::factor() {
if (isdigit(lookahead)) {
string cmd = "push ";
while (isdigit(lookahead)) {
cmd.push_back(lookahead);
lookahead = getchar();
}
pos--;
output.push_back(cmd);
match(lookahead);
} else if (lookahead == '(') {
match('('); expr(); match(')');
} else error();
}
void smToyCompiler::match(char t) {
if (lookahead == t)
lookahead = getchar();
else error();
}
void smToyCompiler::error() {
cout<<"syntax error.\n";
exit(1);
}
int main() {
string expression = "(19*3)-17+(6*2)";
smToyCompiler compiler;
StackMachine sm(false, false);
vector<string> program = compiler.compile(expression);
cout<<"Evaluting: "<<expression<<"\nAnswer: ";
sm.run(program);
return 0;
}