smithy545 smithy545 - 4 months ago 10
Brainfuck Question

Making an if(x==y) statement in Brainfuck

So I'm working on a program that reads in a file and then outputs it back out again but i'm having trouble getting the program to stop taking input at the end of the file. I want it to stop at a specific character like '0' or '$' or anything really since a one character NULL can't be read into my brainf interpreter. Here is the code so far:

>+[>,][<.]


The problem starts at
[>,]
since the input can never be NULL this loop never ends.

So how can I insert an if statement that will terminate this loop if it ever reaches a pre-specified end character?

Answer

The following code is equivalent to your code, except it will stop when the value of the input is 1 (non-printable in ASCII). The < between the loops is reuired because the last value is 0.

>+[+>,-]<[<.]

It decrements the value after input, checks if it is 0, and loops back if it isn't. If it looped back, it must increment the pointer again to undo the decrement. A sample array might be:

00  02  H  e  l  l  o  _  W  o  r  l  d  00
                                          ^

However, the [<.] prints the reverse of the string (followed by a non-printable 1). The string itself can be printed by moving the pointer to the beginning and moving forward from there, as shown in this code:

>+[+>,-]<[<]>>[.>]

In this code, the [<] stops when it reaches index 0, the >> moves to index 2 (string start), and the [.>] outputs characters until it reaches the 0 at the end.

If you want to use a different ASCII character, such as space (32), repeat the + and - within the first loop that many times. (Warning: this code will result in values below 0 if there are any characters less than 32 in your input).

>+[++++++++++++++++++++++++++++++++>,--------------------------------]<[<]>>[.>]