I am trying to make a brainf*** interpreter in c++. when I test it with the Esolang hello world example:
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
is is here: https://esolangs.org/wiki/Brainfuck
it does not print anything for whatever reason. the period operator works, Ive tested it alone, but programs that work on proper brainf*** interpreters don't work on mine. Can anyone find the problem here?
PS:
file_str::read(file);
is a custom method I implemented which works. just to let you know.
this is my code so far.
// Read File
std::string file_data;
file_data = file_str::read(file);
// Array
int array[30000];
bool running = true;
// pos
int pos = 0;
int pos_in_stack = 0;
// Handle brackets
std::vector<int> brackets;
// Main Loop
while(running)
{
if(pos > file_data.size()-1)
{
break;
}
// check what the curren command is and execute
if(file_data.at(pos) == '>')
{
pos_in_stack++;
pos++;
continue;
}
if(file_data.at(pos) == '<')
{
pos_in_stack--;
pos++;
continue;
}
if(file_data.at(pos) == '+')
{
array[pos_in_stack]++;
pos++;
continue;
}
if(file_data.at(pos) == '-')
{
array[pos_in_stack]--;
pos++;
continue;
}
if(file_data.at(pos) == '.')
{
char a = array[pos_in_stack];
std::cout << a;
pos++;
continue;
}
if(file_data.at(pos) == ',')
{
std::string a;
std::cin >> a;
char b = a.at(0);
array[pos_in_stack] = b;
pos++;
continue;
}
if(file_data.at(pos) == '[')
{
if(array[pos_in_stack] != 0)
{
brackets.push_back(pos);
pos++;
continue;
}
// find coresponding bracket
else{
int brackets_looking_for = 1;
while (brackets_looking_for != 0)
{
pos++;
if(file_data.at(pos) == '[')
{
brackets_looking_for++;
}
if(file_data.at(pos) == ']')
{
brackets_looking_for--;
}
}
continue;
}
}
if(file_data.at(pos) == ']')
{
if(array[pos_in_stack] != 0)
{
pos = brackets.at(brackets.size()-1);
continue;
}
brackets.pop_back();
pos++;
continue;
}
}
return 0;
}
Thanks for your help everyone, but I found the solution.
I need to change this:
pos = brackets.at(brackets.size()-1);
to this:
pos = brackets.at(brackets.size()-1)+1;