-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalc.c
More file actions
70 lines (61 loc) · 1.31 KB
/
calc.c
File metadata and controls
70 lines (61 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "parser.h"
#define DEFAULT_PARSER "opp"
#define MAXLINE 1024
static void usage(void)
{
fprintf(stderr, "calc [--parser=<parser>] [--repeat=<count>]\n");
exit(254);
}
int main(int argc, char **argv)
{
const char *parser = DEFAULT_PARSER;
char expr[MAXLINE];
int (*parse)(const char *, int *);
int ret = 0, i;
int repeat = 1, result;
for (i = 1; i < argc; i++) {
const char *arg = argv[i];
if (!strncmp(arg, "--parser=", 9)) {
parser = arg + 9;
continue;
}
if (!strncmp(arg, "--repeat=", 9)) {
repeat = atoi(arg + 9);
continue;
}
if (arg[0] == '-')
usage();
break;
}
if (i != argc)
usage();
if (!strcmp(parser, "rdp"))
parse = rdp_parse_expression;
else if (!strcmp(parser, "opp"))
parse = opp_parse_expression;
else {
fprintf(stderr, "unknown parser '%s'\n", parser);
return -1;
}
while (fgets(expr, MAXLINE, stdin)) {
for (i = 0; i < repeat; i++) {
ret = parse(expr, &result);
if (ret)
break;
}
if (ret) {
static const char *msg[] = {
[ERR_TOK] = "Unknown token",
[ERR_EOL] = "Prematurated EOL",
[ERR_BRACE] = "Unbalanced brace",
[ERR_OP] = "Invalid operator",
};
fprintf(stderr, "Invalid expression, %s\n", msg[ret]);
} else
printf("%d\n", result);
}
return ret;
}