-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstackp.cpp
104 lines (95 loc) · 1.67 KB
/
stackp.cpp
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
#include<iostream>
#include<stack>
#include<cstring>
#include<cstdlib>
using namespace std;
void printStack(stack<int> Stack){
stack<int> tmp;
while(!Stack.empty()){
tmp.push(Stack.top());
cout << Stack.top() << ' ';
Stack.pop();
}
while(!tmp.empty()){
Stack.push(tmp.top());
tmp.pop();
}
cout << endl;
}
int main(int argc, char** argv ){
if(argc<2){
cout << "Argument Error";
return(0);
}
FILE* fp = fopen(argv[1],"rt");
if(fp == NULL){
cout << "File Error.";
return(1);
}
char str[64];
char* stok;
int op = 0;
int arg = 0;
int loop = 0;
stack<int> S;
int tmp1, tmp2;
while(!feof(fp)){
loop++;
fgets(str, 64, fp);
stok = strtok(str,"\n");
stok = strtok(str," ");
op = 0;
arg = 0;
if(!strcmp(stok,"PUSH")) op = 1;
else if(!strcmp(stok,"POP")) op = 2;
else if(!strcmp(stok,"ADD")) op = 3;
else if(!strcmp(stok,"SUB")) op = 4;
else if(!strcmp(stok,"MUL")) op = 5;
else if(!strcmp(stok,"EQUAL")) op = 6;
else if(!strcmp(stok,"SHOW")) op = 7;
if(op==1||op==2){
stok = strtok(NULL," ");
arg = atoi(stok);
}
switch(op){
case 1:
S.push(arg);
break;
case 2:
S.pop();
break;
case 3:
tmp1 = S.top();
S.pop();
tmp2 = S.top();
S.pop();
S.push(tmp1 + tmp2);
break;
case 4:
tmp1 = S.top();
S.pop();
tmp2 = S.top();
S.pop();
S.push(tmp1 - tmp2);
break;
case 5:
tmp1 = S.top();
S.pop();
tmp2 = S.top();
S.pop();
S.push(tmp1 * tmp2);
break;
case 6:
tmp1 = S.top();
S.pop();
tmp2 = S.top();
S.pop();
S.push((tmp1 == tmp2));
break;
case 7:
cout << S.top() << endl;
break;
}
// printStack(S);
}
}