blob: 669ab0ab8609da5f728caceafc7c8f9351be8265 (
plain) (
blame)
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
106
107
108
109
110
111
112
113
114
115
116
117
118
|
/*
+ : Increments the value at the current cell by one.
- : Decrements the value at the current cell by one.
> : Moves the data pointer to the next cell (cell on the right).
< : Moves the data pointer to the previous cell (cell on the left).
. : Prints the ASCII value at the current cell (i.e. 65 = 'A').
, : Reads a single input character into the current cell.
[ : If the value at the current cell is zero, skips to the corresponding ] .
Otherwise, move to the next instruction.
] : If the value at the current cell is zero, move to the next instruction.
Otherwise, move backwards in the instructions to the corresponding [ .
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DATA 30000
typedef struct brainfuck{
char data[MAX_DATA];
char command[MAX_DATA];
char *ptr;
int count;
int pos;
}bf;
bf one;
void init()
{
char c;
memset(&one, 0, sizeof(one));
one.pos = 0;
one.count = 0;
one.ptr = one.data;
while (c = getchar())
{
if (c == '\n')
break;
else
{
one.command[++one.count] = c;
}
}
one.command[one.count] = '\0';
}
void run()
{
char c;
int i;
while (c = one.command[++one.pos])
{
switch (c)
{
case '+':
(*one.ptr)++;
break;
case '-':
(*one.ptr)--;
break;
case '>':
one.ptr++;
break;
case '<':
one.ptr--;
break;
case ',':
*one.ptr = getchar();
break;
case '.':
putchar(*one.ptr);
break;
case '[':
if (*one.ptr != 0)
break;
else
{
for (i = one.pos + 1; i <= one.count; i++)
{
if (one.command[i] == ']')
{
one.pos = i;
break;
}
}
}
break;
case ']':
if (*one.ptr == 0)
break;
else
{
for (i = one.pos - 1; i >= 1; i--)
{
if (one.command[i] == '[')
{
one.pos = i;
break;
}
}
}
break;
}
}
}
int main(int argc, char **argv)
{
if (argc > 1) {
freopen(argv[1], "r", stdin);
}
init();
run();
return 0;
}
|