aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'brainfuck/brainfuck/main.cpp')
-rw-r--r--brainfuck/brainfuck/main.cpp117
1 files changed, 117 insertions, 0 deletions
diff --git a/brainfuck/brainfuck/main.cpp b/brainfuck/brainfuck/main.cpp
new file mode 100644
index 0000000..b1e0afa
--- /dev/null
+++ b/brainfuck/brainfuck/main.cpp
@@ -0,0 +1,117 @@
1/*
2+ : Increments the value at the current cell by one.
3- : Decrements the value at the current cell by one.
4> : Moves the data pointer to the next cell (cell on the right).
5< : Moves the data pointer to the previous cell (cell on the left).
6. : Prints the ASCII value at the current cell (i.e. 65 = 'A').
7, : Reads a single input character into the current cell.
8[ : If the value at the current cell is zero, skips to the corresponding ] .
9Otherwise, move to the next instruction.
10] : If the value at the current cell is zero, move to the next instruction.
11Otherwise, move backwards in the instructions to the corresponding [ .
12*/
13#include <stdio.h>
14#include <stdlib.h>
15#include <string.h>
16
17#define MAX_DATA 30000
18
19typedef struct brainfuck{
20 char data[MAX_DATA];
21 char command[MAX_DATA];
22 char *ptr;
23 int count;
24 int pos;
25}bf;
26
27bf one;
28
29void init()
30{
31 char c;
32 memset(&one, 0, sizeof(one));
33 one.pos = 0;
34 one.count = 0;
35 one.ptr = one.data;
36
37 while (c = getchar())
38 {
39 if (c == '\n')
40 break;
41 else
42 {
43 one.command[one.count++] = c;
44 }
45 }
46}
47
48void run()
49{
50 char c;
51 int i;
52
53 while (c = one.command[one.pos++])
54 {
55 switch (c)
56 {
57 case '+':
58 (*one.ptr)++;
59 break;
60 case '-':
61 (*one.ptr)--;
62 break;
63 case '>':
64 one.ptr++;
65 break;
66 case '<':
67 one.ptr--;
68 break;
69 case ',':
70
71 break;
72 case '.':
73 putchar(*one.ptr);
74 break;
75 case '[':
76 if (*one.ptr)
77 break;
78 else
79 {
80 for (i = one.pos; i < one.count; i++)
81 {
82 if (one.command[i] == ']')
83 {
84 one.pos = i;
85 break;
86 }
87 }
88 }
89 break;
90 case ']':
91 if (*one.ptr)
92 break;
93 else
94 {
95 for (i = one.pos; i >= 0; i--)
96 {
97 if (one.command[i] == '[')
98 {
99 one.pos = i;
100 break;
101 }
102 }
103 }
104 break;
105 }
106 }
107}
108
109int main(int argc, char **argv)
110{
111 if (argc > 1) {
112 freopen(argv[1], "r", stdin);
113 }
114 init();
115 run();
116 return 0;
117} \ No newline at end of file
Powered by cgit v1.2.3 (git 2.41.0)