forked from BayLibre/calculator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc.c
88 lines (75 loc) · 1.45 KB
/
calc.c
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
struct calc_func {
int (*compute)();
char key;
char *name;
};
int add() {
int x, res=0;
char cmd[20];
printf("Enter numbers to add\n");
while( fgets(cmd, 20, stdin) && cmd[0] != '\n' ) {
res += atoi(cmd);
}
printf("Result is %d\n", res);
}
int subtract() {
int x, res=0;
char cmd[20];
printf("Enter numbers to subtract\n");
while( fgets(cmd, 20, stdin) && cmd[0] != '\n' ) {
res -= atoi(cmd);
}
printf("Result is %d\n", res);
}
int quit() {
printf("Good Bye\n");
exit(0);
}
struct calc_func functions[] = {
{
.key = 'q',
.compute = quit,
.name = "quit",
},
{
.key = '+',
.compute = add,
.name = "addition",
},
{
.key = '-',
.compute = subtract,
.name = "subtraction",
}
};
#define NB_FUNCS (sizeof(functions)/sizeof(struct calc_func))
void print_function(struct calc_func *f) {
}
void print_all_functions() {
int i;
for (i = 0 ; i < NB_FUNCS ; i++) {
printf("Press key %c for %s\n", functions[i].key, functions[i].name);
}
}
int main(){
int i;
char cmd[20];
printf("Welcome to Calculator 2.0 \n");
printf("========================= \n\n");
print_all_functions();
printf("========================= \n\n");
while(1) {
printf("Enter a command\n");
fgets(cmd, 20, stdin);
for (i = 0 ; i < NB_FUNCS ; i++) {
if (functions[i].key == cmd[0]) {
printf("Calling command: %s\n", functions[i].name);
functions[i].compute();
break;
}
}
}
}