-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbrainfuck.cpp
More file actions
86 lines (81 loc) · 2.38 KB
/
brainfuck.cpp
File metadata and controls
86 lines (81 loc) · 2.38 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
#include <string>
#include <fstream>
#include <streambuf>
#include <sstream>
#include <iostream>
#include <stdio.h>
class BrainFuck {
private:
std::string code;
size_t iptr = 0;
size_t dptr = 0;
char *data = (char*)calloc(30000, sizeof(char));
public:
BrainFuck(std::string c){
this->code = c;
}
void run(){
size_t iptr_MAX = this->code.length();
for(; iptr < iptr_MAX; iptr++){
size_t count = 1;
switch(this->code[iptr]){
case '>':
this->dptr++;
break;
case '<':
this->dptr--;
break;
case '+':
this->data[this->dptr]++;
break;
case '-':
this->data[this->dptr]--;
break;
case '.':
std::cout << this->data[this->dptr];
break;
case ',':
this->data[this->dptr] = (char)getchar();
break;
case '[':
if(!this->data[this->dptr]){
this->iptr++;
while(count > 0){
if(code[iptr] == '['){
count++;
}
else if(code[iptr] == ']'){
count--;
}
iptr++;
}
iptr--;
}
break;
case ']':
if(this->data[this->dptr]){
this->iptr--;
while(count > 0){
if(this->code[this->iptr] == ']'){
count++;
}
else if(this->code[this->iptr] == '['){
count--;
}
iptr--;
}
}
break;
default:
break;
}
}
}
};
int main(int argc, char **argv){
std::ifstream s(argv[1]);
std::stringstream tmp;
tmp << s.rdbuf();
BrainFuck bf = BrainFuck(tmp.str());
bf.run();
}