The original written in C
Code: Select all
#include <stdio.h>
#include <stdlib.h>
#define MAX_FILENAME 300
static char *ptr;
int do_command(const char command, FILE *pFile)
{
char c;
int pos;
switch (command)
{
case '>':
++ptr;
break;
case '<':
--ptr;
break;
case '+':
++*ptr;
break;
case '-':
--*ptr;
break;
case '.':
putchar(*ptr);
break;
case ',':
*ptr=getchar();
break;
case '[':
pos = ftell(pFile);
while (*ptr)
{
fseek(pFile, pos, SEEK_SET);
c = getc(pFile);
while (c != ']' && c != EOF)
{
do_command(c, pFile);
c = getc(pFile);
}
}
break;
}
}
int parse_source(const char *source)
{
char command; // Stores each command
FILE *pFile = fopen(source, "r");
if (pFile) // If we were able to open the file
{
while ((command = getc(pFile)) != EOF) // For each character in file
{
do_command(command, pFile); // Execute command
}
}
else
{
printf("File could not be read.");
}
fclose(pFile);
}
int main(int argc, const char *argv[])
{
int memory[9001]; // Make array to store values in
ptr = &memory; // Put it into the global pointer
parse_source(argv[1]); // Parse the source file defined in argument
return 0;
}
The C++ conversion
Code: Select all
#define BRAINF_ARRAY 100
class Brainf
{
public:
Brainf(){ bf = (char*)mem; }
~Brainf(){ bf = NULL;
delete bf; }
void Parse(std::string line)
{
int position=0;
const char *str = line.c_str();
char cmd;
while (position != line.length())
{
cmd=str[position];
switch (cmd)
{
// THESE CASES ARE ALL THE SAME EXCEPT THE ONE BELOW
// SO I HAVE OMITTED THEM FROM THE CODE FOR LENGTH REASONS
case '[':
{
std::string tmp;
position++; // If you find '[' add one to the position, so that I don't create an infinite loop of [
while (*bf)
{
while (cmd != ']')
{
cmd=str[position]; // AS FAR AS I KNOW: This code should append each command after '[' and before ']'
tmp += cmd; // to the string 'tmp' and add one to the position afterward, before going back and doing it again
position++; // However, the output of the string I input should be "Hello world!" just for testing,
} // and it works properly with the C code. But instead outputs characters it isn't supposed to.
Parse(tmp); // I know it's because of this loop segment, or perhaps with the position it's looping through.
}
}
break;
}
position++; // After each character of the array is parsed, the position is increased
}
}
private:
// std::fstream file;
int mem[BRAINF_ARRAY];
// bf = &memory;
char *bf;
};
I realize this is a lot of code to post, but most of it is near the same, so I've omitted it from the C++ conversion. I know this is probably some stupid mistake on my part. I also realize supplying this much code is a major stretch on my part, but commented it thoroughly and have tried to fix it for a long time now. Here is the brainfuck code that should output "Hello world!"...
Code: Select all
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.