在一个c brainstfuck解释器中实现循环



我用c编写了一个简单的brainfuck解释器。除了循环,所有命令都能正常工作。目前,我正在这样处理它们:

我有一个功能可以找到匹配的方括号:

int findbracket(char *commands, int currentpos){
int lb = 0;
int rb = 0;
for(int i = currentpos; i != strlen(commands); ++i){
if(commands[i] == '[') ++lb;
if(commands[i] == ']') ++rb;
if(lb == rb){
return i;
}
}
}

我有一个堆栈来跟踪所有的括号:

void interpret(char *commands){
int stack[10];
int top = 0;
for(int i = 0; i < strlen(commands); ++i){
char command = commands[i];

//other commands...
else if(command == '['){
if(*ptr == 0){
i = findbracket(commands, i);
}
else{
stack[top] = i;
++top;
}
}
else if(command == ']'){
if(*ptr != 0){
i = stack[top];
}
else{
--top;
}
}
}
}

然而,这似乎并不奏效。例如,当执行helloworld:++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.时,它根本没有输出。我做错了什么?

您想要:

if(*ptr != 0){
i = stack[top-1];
}

"顶部";标记下一个东西将在堆栈上的位置,就在添加最后一个东西的位置的上方。

最新更新