How to have text before the input in Brainfuck?

85 views Asked by At

How do I make it so that the question is asked before the input in Brainfuck?

What I want:

What is your number:
3

What I get:

3
What is your number:

So the input executes before the text is printed even though the text is written first in the code.

My code:

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

As you can see the , is placed behind the part that writes "What is your number:" but it executes before that.

I would really appreciate it if someone would know the answer.

1

There are 1 answers

0
Daniel Cristofani On

What's happening here is probably line-buffering. When the '.' command is executed, the output character gets stored in a buffer, and when a whole line of text has been stored it outputs the whole line at once. This is implementation-dependent; it's not specifically a brainfuck thing. Some brainfuck interpreters line-buffer, some don't, and the interpreter writer may not have even thought about it but just inherited behavior from whatever language the interpreter is written in.

Even when line-buffering is happening, it seems odd that executing a read doesn't release the buffer (which would output the question before the answer is input, producing correct/expected behavior). That would be the usual behavior for, say, a simple terminal-based implementation using getchar/putchar or similar. I'm interested to know what brainfuck implementation you're using that's getting this wrong.

Anyway, to output the question first on that implementation, you probably need to output a linefeed (10) at the end of the question. That means you can't put a prompt where the user can enter the answer on the same line, which is a small awkwardness.

I would note that if you're interested in writing code that will be widely portable, a bigger problem will be that you assume cells are bytes. They often/mostly are, but a fair number of implementations use larger cells and that means your program will print the wrong thing slowly.