C语言实现Basic语言

C语言实现Basic语言,给出C语言实现代码

以下是一个简单的C语言实现Basic语言的示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE_LENGTH 1000
#define MAX_VARIABLES 100

typedef struct {
    char name[20];
    int value;
} Variable;

Variable variables[MAX_VARIABLES];
int variableCount = 0;

void executeCommand(char* line);
void parseAssignment(char* line);
void parsePrint(char* line);

int main() {
    char line[MAX_LINE_LENGTH];

    while (1) {
        printf(">> ");
        fgets(line, MAX_LINE_LENGTH, stdin);

        if (strcmp(line, "QUIT\n") == 0) {
            break;
        }

        executeCommand(line);
    }

    return 0;
}

void executeCommand(char* line) {
    if (strncmp(line, "PRINT", 5) == 0) {
        parsePrint(line);
    } else {
        parseAssignment(line);
    }
}

void parseAssignment(char* line) {
    char varName[20];
    int varValue;

    sscanf(line, "%s = %d", varName, &varValue);

    for (int i = 0; i < variableCount; i++) {
        if (strcmp(variables[i].name, varName) == 0) {
            variables[i].value = varValue;
            return;
        }
    }

    Variable variable;
    strcpy(variable.name, varName);
    variable.value = varValue;

    variables[variableCount++] = variable;
}

void parsePrint(char* line) {
    char varName[20];

    sscanf(line, "PRINT %s", varName);

    for (int i = 0; i < variableCount; i++) {
        if (strcmp(variables[i].name, varName) == 0) {
            printf("%s = %d\n", variables[i].name, variables[i].value);
            return;
        }
    }

    printf("Variable %s not found\n", varName);
}

这个实现简单地解析用户输入的命令,并根据命令类型执行不同的操作。目前支持两个命令:赋值命令和打印命令。赋值命令形如变量名 = 值,将值赋给对应的变量。打印命令形如PRINT 变量名,输出对应变量的值。用户可以通过输入"QUIT"来退出程序。