-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
126 lines (97 loc) · 1.9 KB
/
main.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_EXPR_LENGTH 100
char *removeAllSpaces(char *line);
int getInt(char *line, int index);
int readExpr(char *line, int index);
int main(void)
{
char *line = malloc(sizeof(char) * MAX_EXPR_LENGTH);
int res;
while (1)
{
printf("Enter an expression (or 'quit'): ");
fgets(line, MAX_EXPR_LENGTH, stdin);
line[strlen(line) - 1] = '\0';
if (strcmp(line, "quit") == 0)
{
printf("Goodbye!\n");
return 0;
}
line = removeAllSpaces(line);
res = readExpr(line, 0);
printf("Result: %d\n", res);
}
return 0;
}
int readExpr(char *line, int index)
{
char op;
int number = getInt(line, index);
// get how far we moved up after getting the number (with getInt)
int tempNumber = number;
int tempIndex = 0;
while (1)
{
tempIndex++;
tempNumber /= 10;
if (tempNumber == 0)
{
break;
}
}
int newIndex = index + tempIndex;
if (newIndex + 1 > strlen(line))
{
return number;
}
op = line[newIndex];
if (op == '+')
{
return number + readExpr(line, newIndex + 1);
}
else if (op == '-')
{
return number - readExpr(line, newIndex + 1);
}
else if (op == '*')
{
return number * readExpr(line, newIndex + 1);
}
}
char *removeAllSpaces(char *line)
{
char *newStr = NULL;
int i, j = 0;
for (i = 0; i < strlen(line); i++)
{
if (line[i] == ' ')
{
continue;
}
j++;
newStr = realloc(newStr, sizeof(char) * j);
newStr[j - 1] = line[i];
}
printf("%s\n", newStr);
return newStr;
}
int getInt(char *line, int index)
{
int j = 0;
char *strInt = NULL;
while (1)
{
if (!isdigit(line[index]) || index > strlen(line))
{
break;
}
j++;
strInt = realloc(strInt, sizeof(char) * j);
strInt[j - 1] = line[index];
index++;
}
return atoi(strInt);
}