-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoutput.cpp
More file actions
105 lines (104 loc) · 4.01 KB
/
output.cpp
File metadata and controls
105 lines (104 loc) · 4.01 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <cstdlib>
#include "std.hpp"
void println(std::string s) {
std::cout << s << std::endl;
}
std::string input() {
std::string line;
std::getline(std::cin, line);
return line;
}
int len(std::string s) {
return s.size();
}
std::string charAt(std::string s, int i) {
return std::string(1, s.at(i));
}
std::string toString(int s) {
return std::to_string(s);
}
std::string fromASCII(int ascii) {
return std::string(1, static_cast<char>(ascii));
}
void bf(std::string code)
{
std::vector<int> tape = {0};
int ptr = 0;
int code_len = len(code);
int code_ptr = 0;
std::vector<int> loop_stack = {0};
while ((code_ptr < code_len)) {
std::string command = charAt(code, code_ptr);
if ((command == ">")) {
ptr += 1;
if ((ptr == tape.size())) {
tape.push_back(0);
}
}
else
if ((command == "<")) {
if ((ptr > 0)) {
ptr -= 1;
}
}
else
if ((command == "+")) {
tape[ptr] += 1;
}
else
if ((command == "-")) {
tape[ptr] -= 1;
}
else
if ((command == ".")) {
println(fromASCII(tape[ptr]));
}
else
if ((command == ",")) {
std::string input_char = input();
if ((len(input_char) > 0)) {
tape[ptr] = static_cast<int>(static_cast<unsigned char>(input_char.at(0)));
}
}
else
if ((command == "[")) {
if ((tape[ptr] == 0)) {
int open_brackets = 1;
while ((open_brackets > 0)) {
code_ptr += 1;
if ((charAt(code, code_ptr) == "[")) {
open_brackets += 1;
}
else
if ((charAt(code, code_ptr) == "]")) {
open_brackets -= 1;
}
}
}
else {
loop_stack.push_back(code_ptr);
}
}
else
if ((command == "]")) {
if ((tape[ptr] != 0)) {
code_ptr = loop_stack[(loop_stack.size() - 1)];
}
else {
loop_stack.pop_back();
}
}
code_ptr += 1;
}
}
int main()
{
println("Enter bf code: ");
std::string x = input();
bf(x);
return 0;
}