2

我正在尝试用C++编写一个简单的笨蛋解释器。到目前为止它工作得很好,但它忽略了字符输入命令(',')。

口译员:

#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';
}

打破一切的 UtraSimple 脑残代码:

,.

有谁知道是什么导致它跳过输入字符?

4

1 回答 1

7

我会先看看这个:

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

将在那里处理的第一个字符将是code[1]而不是 code[0]

因此程序将",."首先处理(字符串结尾),因此不会处理输入命令。.\0,

如果您将代码更改如下,您可以看到这一点:

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

你会看到:

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

你需要推迟递增i,直到你完成它

于 2013-01-30T03:39:25.587 回答