Add main.c for a driver demo
parent
8fefe97975
commit
f937af9cbe
|
|
@ -0,0 +1,72 @@
|
||||||
|
/*
|
||||||
|
* Simple REPL for the calc evaluator.
|
||||||
|
* Build: calc main.c -o calc -lm
|
||||||
|
* @author Abner Coimbre <abner@terminal.click>
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <math.h>
|
||||||
|
#include <assert.h>
|
||||||
|
#include <ctype.h>
|
||||||
|
|
||||||
|
/* 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;
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue