From f937af9cbe63a91524fbfc6923028987690707a3 Mon Sep 17 00:00:00 2001 From: Abner Coimbre Date: Sun, 15 Mar 2026 10:56:38 -0700 Subject: [PATCH] Add main.c for a driver demo --- main.c | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 main.c diff --git a/main.c b/main.c new file mode 100644 index 0000000..22fd0dd --- /dev/null +++ b/main.c @@ -0,0 +1,72 @@ +/* + * Simple REPL for the calc evaluator. + * Build: calc main.c -o calc -lm + * @author Abner Coimbre + */ + +#include +#include +#include +#include +#include +#include + +/* Macros expected by tc_calc.h / tc_calc.c */ +#define function static +#define global static +#define cast(T) (T) + +#ifndef TC_CALC_FORMAT_BUFFER_SIZE +#define TC_CALC_FORMAT_BUFFER_SIZE 256 +#endif + +#include "tc_calc.h" +#include "tc_calc.c" + +#define INPUT_MAX 1024 + +int main(void) +{ + char buf[INPUT_MAX]; + calc_FormatKind fmt = CALC_FORMAT_DECIMAL; + + printf("calc> "); + fflush(stdout); + + while (fgets(buf, sizeof buf, stdin)) { + /* strip trailing newline */ + buf[strcspn(buf, "\n")] = '\0'; + + /* skip blank lines */ + if (buf[0] == '\0') { + printf("calc> "); + fflush(stdout); + continue; + } + + /* format switching commands */ + if (strcmp(buf, ":dec") == 0) { + fmt = CALC_FORMAT_DECIMAL; + printf(" format: decimal\n"); + } else if (strcmp(buf, ":hex") == 0) { + fmt = CALC_FORMAT_HEX; + printf(" format: hex\n"); + } else if (strcmp(buf, ":bin") == 0) { + fmt = CALC_FORMAT_BINARY; + printf(" format: binary\n"); + } else { + double result = calc_eval(buf); + + if (isnan(result)) + printf(" error: invalid expression\n"); + else + printf(" %s\n", calc_format_result(result, fmt)); + } + + printf("calc> "); + fflush(stdout); + } + + putchar('\n'); + return 0; +}