I written a Interpreter in C++ for Brainfuck und it works fine with "Hello World" Brainfuck Code to give me the right output. Now I'm trying a different Brainfuck Code, that generates the fibonacci number sequence, but now it just won't work and is just printing some weird symbols and random numbers in the console.
Here is the Code:
#include <cstring>
#include <iostream>
#include <vector>
class BrainFuckInterpreter
{
private:
std::vector<unsigned char> memory;
size_t pointer;
public:
BrainFuckInterpreter()
: memory(30000000, 0)
, pointer(0)
{
}
void Interpret(const std::string& code)
{
size_t i = 0;
std::vector<size_t> temp;
while (i < code.length())
{
char input = code[i];
switch (input)
{
case '>':
++pointer;
break;
case '<':
--pointer;
break;
case '+':
++memory[pointer];
break;
case '-':
--memory[pointer];
break;
case '[':
temp.push_back(i);
break;
case ']':
if (memory[pointer] != 0)
{
i = temp.back();
}
else
{
temp.pop_back();
}
break;
case '.':
std::cout << memory[pointer];
break;
case ',':
std::cin >> memory[pointer];
break;
default:
break;
}
i++;
}
}
};
int main()
{
std::string code = R"(+++++++++++
>+>>>>++++++++++++++++++++++++++++++++++++++++++++
>++++++++++++++++++++++++++++++++<<<<<<[>[>>>>>>+>
+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<[>++++++++++[-
<-[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<[>>>+<<<
-]>>[-]]<<]>>>[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]
>[<<+>>[-]]<<<<<<<]>>>>>[+++++++++++++++++++++++++
+++++++++++++++++++++++.[-]]++++++++++<[->-<]>++++
++++++++++++++++++++++++++++++++++++++++++++.[-]<<
<<<<<<<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<-[>>.>.<<<
[-]]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+>-]>[<+>-]<<<-])";
BrainFuckInterpreter bfint;
bfint.Interpret(code);
}
Console Output : , 8 , = , E } , R , g K , Expected Output : 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
What I tried:
case '.':
// Output the numerical value without additional characters
std::cout << static_cast<int>(memory[pointer]) << " ";
break;
There I got this Output: 49 49 44 32 49 49 44 32 50 40 44 32 51 31 44 32 53 13 44 32 56 242 44 32 61 197 44 32 69 125 44 32 82 8 44 32 103 75 44 32 137 25 44 32
Then I tried that:
case '.':
// Output the numerical value as a character
putc(memory[pointer], stdout);
break;
Output: , 8‗, =┼, E } , , gK, ë↓,
Next Try:
case '.':
// Output the numerical value as a character
putc(static_cast<char>(memory[pointer]), stdout);
fflush(stdout);
break;
Output: , 8‗, =┼, E } , , gK, ë↓,
Next Try:
int main()
{
// Set console code page to UTF-8 (Windows)
system("chcp 65001");
Output: , 8, =, E}, , gK, ,