经过一,上篇简单是是表达式的,并表达式,并输入,并输入则则运算见谅 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_INPUT 256
#define TYPE_INT 1
#define TYPE_STRING 2
#define TYPE_LIST 3
typedef struct {
int type;
union {
int i;
char *s;
struct {
void **data;
int size;
} l;
} value;
} Object;
Object *new_object(int type) {
Object *obj = (Object *)malloc(sizeof(Object));
obj->type = type;
return obj;
}
void free_object(Object *obj) {
if (obj->type == TYPE_STRING) {
free(obj->value.s);
} else if (obj->type == TYPE_LIST) {
for (int i = 0; i < obj->value.l.size; i++) {
free_object((Object *)obj->value.l.data[i]);
}
free(obj->value.l.data);
}
free(obj);
}
Object *parse_expression(char *input) {
// TODO: 解析表达式并返回计算结果
return NULL;
}
int main() {
char input[MAX_INPUT];
Object *result;
while (1) {
printf(">> ");
fgets(input, MAX_INPUT, stdin);
if (strcmp(input, "exit\n") == 0) {
exit(0);
} else {
result = parse_expression(input);
if (result != NULL) {
if (result->type == TYPE_INT) {
printf("%d\n", result->value.i);
} else if (result->type == TYPE_STRING) {
printf("%s\n", result->value.s);
} else if (result->type == TYPE_LIST) {
printf("[");
for (int i = 0; i < result->value.l.size; i++) {
Object *item = (Object *)result->value.l.data[i];
if (item->type == TYPE_INT) {
printf("%d", item->value.i);
} else if (item->type == TYPE_STRING) {
printf("'%s'", item->value.s);
}
if (i != result->value.l.size - 1) {
printf(", ");
}
}
printf("]\n");
}
free_object(result);
} else {
printf("Invalid input\n");
}
}
}
return 0;
}
|