-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackCalculator.cpp
More file actions
117 lines (113 loc) · 2.16 KB
/
StackCalculator.cpp
File metadata and controls
117 lines (113 loc) · 2.16 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
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
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100
int top;
int num[MAX];
void Push(int);
int Pop();
int Test_Full();
int Test_Empty();
void print();
/* This main function read data in file
And traslate string line to operand and operator
Also calculate this string.
This result values will write new file
Fianally printf this new file data
Switch library function controls operation using stack(pop and push)*/
void main()
{
int data;
int tmp1, tmp2;
char *token;
char delimit[] = " \n";
char line[255];
char *tmp;
int button;
FILE *fp;
FILE *FP;
fp = fopen("lab2-1.txt", "r");
FP = fopen("result.txt", "w");
if (fp == NULL)
{
printf("File read failed.\n");
exit(1);
}
top = -1;
button = 1;
while (fgets(line, 255, fp))
{
token = strtok(line, delimit);
while (token != NULL)
{
printf("%s ", token);
fprintf(FP, "%s ", token);
switch (*token)
{
case '*':
tmp1 = Pop();
tmp2 = Pop();
Push(tmp1*tmp2);
break;
case '+':
tmp1 = Pop();
tmp2 = Pop();
Push(tmp1 + tmp2);
break;
case '-':
tmp1 = Pop();
tmp2 = Pop();
Push(tmp2 - tmp1);
break;
default:
data = atoi(token);
Push(data);
break;
}
token = strtok(NULL, delimit);
}
printf(" = %d \n", num[top]);
fprintf(FP, "%d \n", num[top]);
top = -1;
}
fclose(fp);
fclose(FP);
}
//This push function is used to insert new data.
//Input: New Data from main function
//Output: None.
void Push(int DATA)
{
top++;
num[top] = DATA;
}
//This pop function is used to delete data(The last inserted data).
//Input: None
//Output: deleted data.
int Pop()
{
int tmp;
tmp = top;
top--;
return num[tmp];
}
//This Test Full function checks data storage is full.
//Input: None
//Output: return false or true (stack is full or not full)
int Test_Full()
{
if (top == MAX - 1)
return -1;
else
return 1;
}
//This Test Empty function checks data storage is Empty.
//Input: None
//Output: return false or true (stack is empty or not empty)
int Test_Empty()
{
if (top == -1)
return -1;
else
return 1;
}