So im trying to code a very very simple brainfuck interpreter in c, and i run into problems while trying to outprint certain characters by what i understand (please keep in mind i just started c so im not doing any complicated stuff with pointers yet)
This is all my code:
> #include <stdio.h>
int bla(char tabukaz[30000], int ukaz, int num) {
int sum=0;
int index=ukaz;
while (sum>-1) {
index-=num;
if (tabukaz[index]==']') sum+=num;
else if (tabukaz[index]=='[') sum-=num;
}
return index;
}
int main () {
int tab[30000];
int tabukaz[30000];
int c;
int i = 0; int ukaz = 0;
unsigned char ch;
for (int i = 0; i < 30000; i++) {
tab[i]=0;
tabukaz[i]=0;
}
while ((c=getchar())!=EOF) {
ch = (unsigned char)c;
if (ch == '>' || ch == '<' || ch == '+' || ch == '-' || ch == '.' || ch == '[' || ch == ']') {
tabukaz[ukaz]=ch;
}
switch (ch) {
case '>': i++; break;
case '<': i--; break;
case '+': tab[i]++;break;
case '-': tab[i]--; break;
case '.': putchar(tab[i]); break;
case '[':
if (tab[i]==0) {
ukaz = bla(tabukaz, ukaz, -1);
}
break;
case ']':
if (tab[i]!=0) {
ukaz = bla(tabukaz, ukaz, 1);
}
break;
default: break;
}
ukaz++;
}
return 0;
}
This is the input in question (i tried to avoid the other text in the actual input (keep in mind everything down here is part of the input, even the unnecessary text) We got provided with a make file which will write the output into a text file, and compare it to a predefined text, the problem is my text file comes out as a binary file and i cant figure out why. The problem may be hidden in how i handle [ and ] as i didnt have that problem in the earlier tests without them
+++++ +++++ initialize counter (cell #0) to 10
[ use loop to set 70/100/30/10
> +++++ ++ add 7 to cell #1
> +++++ +++++ add 10 to cell #2
> +++ add 3 to cell #3
> + add 1 to cell #4
<<<< - decrement counter (cell #0)
]
> ++ . print 'H'
> + . print 'e'
+++++ ++ . print 'l'
. print 'l'
+++ . print 'o'
> ++ . print ' '
<< +++++ +++++ +++++ . print 'W'
> . print 'o'
+++ . print 'r'
----- - . print 'l'
----- --- . print 'd'
> + . print '!'
> . print '\n'
Aucun commentaire:
Enregistrer un commentaire