-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interpreter_CPP_version.cpp
85 lines (80 loc) · 2.04 KB
/
Interpreter_CPP_version.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
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;
void interpret(string code){
int memory[30000];
int pointer = 0;
bool isLooping = false;
stack<int> loopStack;
int innerLoops = 0;
for(int i=0; i< code.length(); i++) {
char c = code[i];
if(isLooping) {
if(c=='[')
innerLoops++;
else if(c==']')
if(innerLoops==0)
isLooping = false;
else
innerLoops--;
continue;
}
switch(c) {
case '>':
pointer++;
break;
case '<':
pointer--;
break;
case '+':
memory[pointer]++;
break;
case '-':
memory[pointer]--;
break;
case '.':
cout << (char)memory[pointer];
break;
case ',':
cin >> memory[pointer];
break;
case '[':
if(memory[pointer]==0)
isLooping = true;
else
loopStack.push(i);
break;
case ']':
if(memory[pointer]!=0)
i = loopStack.top();
else
loopStack.pop();
break;
}
}
}
int main(){
string code;
ifstream file("brainf.txt");
if(file.is_open()){
string line;
while(getline(file, line))
code += line;
file.close();
}
else
cout << "Unable to open file";
int openBrackets = 0;
int closeBrackets = 0;
for(int i = 0; i < code.length(); i++)
if(code[i] == '[')
openBrackets++;
else if(code[i] == ']')
closeBrackets++;
if(openBrackets == closeBrackets)
interpret(code);
else
cerr << "Error: Number of open brackets does not match number of close brackets";
return 0;
}