DelishusCake DelishusCake - 4 months ago 15
Brainfuck Question

Program is ignoring input

I'm trying to write a simple brainfuck interpreter in C++. It works great so far, but it ignores the character input command (',').

The Interpreter:

#include <iostream>
#include <fstream>
#include <windows.h>
using namespace std;

#define SIZE 30000

void parse(const char* code);

int main(int argc, char* argv[])
{
ifstream file;
string line;
string buffer;
string filename;

cout << "Simple BrainFuck interpreter" << '\n';
cout << "Enter the name of the file to open: ";
cin >> filename;
cin.ignore();

file.open(filename.c_str());
if(!file.is_open())
{
cout << "ERROR opening file " << filename << '\n';
system("pause");
return -1;
}
while (getline(file, line)) buffer += line;

parse(buffer.c_str());

system("pause");
return 0;
}
void parse(const char* code)
{
char array[SIZE];
char* ptr = array;

char c;
int loop = 0;
unsigned int i = 0;
while(i++ < strlen(code))
{
switch(code[i])
{
case '>': ++ptr; break;
case '<': --ptr; break;
case '+': ++*ptr; break;
case '-': --*ptr; break;
case '.':
cout << *ptr;
break;
case ',':
cin >> *ptr;
break;
case '[':
if (*ptr == 0)
{
loop = 1;
while (loop > 0)
{
c = code[++i];
if (c == '[') loop ++;
else if (c == ']') loop --;
}
}
break;
case ']':
loop = 1;
while (loop > 0)
{
c = code[--i];
if (c == '[') loop --;
else if (c == ']') loop ++;
}
i --;
break;
}
}
cout << '\n';
}


The UtraSimple brainfuck code that breaks everything:

,.


Does anyone know what causes it to skip the input character?

Answer

I'd be looking at this for a start:

unsigned int i = 0;
while(i++ < strlen(code))  // increments i NOW !
{
    switch(code[i])        // uses the incremented i.

The first character that will get processed there will be code[1], not code[0].

So the program ",." will first process . then \0 (end of string) hence there will be no input command , processed.

You can see this if you change the code as follows:

unsigned int i = 0;
while(i++ < strlen(code))
{
    cout << "DEBUG [" << i << ":" << (int)code[i] << ":" << code[i] << "]\n";
    switch(code[i])

and you'll see:

DEBUG [1:46:.]
DEBUG [2:0: ]

You need to hold off on incrementing i until after you're finished with it.