-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpvalidator.cpp
More file actions
121 lines (102 loc) · 2.09 KB
/
expvalidator.cpp
File metadata and controls
121 lines (102 loc) · 2.09 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
118
119
120
121
/**
* Author: Hemant Tripathi
*/
#include <iostream>
using namespace std;
#define MAXSIZE 20
class Expression {
int top;
public:
char expression[MAXSIZE];
Expression() {
top = -1;
}
bool Push(char x);
bool Pop(char x);
char GetTop();
bool IsEmpty();
};
bool Expression::Push(char x) {
if(top >= MAXSIZE) {
cout << "Buffer Full Error" << endl;
return false;
} else {
cout << "Entering element into stack : " << x << endl;
expression[++top] = x;
return true;
}
}
bool Expression::Pop(char x) {
cout << "Top Value = " << top << endl;
cout << "Popping item = "<<x<<endl;
if(top < 0) {
cout << "Stack is Empty" << endl;
return false;
} else {
char poppeditem = expression[top];
if((x == ')' && poppeditem == '(') || (x == '}' && poppeditem == '{') || (x == ']' && poppeditem == '[')) {
//Pop an item
top--;
return true;
} else {
return false;
}
}
}
char Expression::GetTop() {
if(top < 0) {
return 'x';
} else {
return expression[top];
}
}
bool Expression::IsEmpty() {
if(top < 0) {
return true;
} else {
return false;
}
}
int main() {
class Expression expression;
string input;
char inputarr[50];
bool isValid = true;
cout << "Write an expression to validate" << endl;
cin >> input;
char *ptr;
int counter = 0;
for(auto x: input) {
if(x == '\0')
break;
inputarr[counter++] = x;
}
inputarr[counter] = '\0';
ptr = inputarr;
while(*ptr != '\0') {
cout << "next character: "<<*ptr << endl;
if(*ptr == '(' || *ptr == '{' || *ptr == '[') {
//push the character into stack
bool isPushed = expression.Push(*ptr);
if(!isPushed) {
isValid = false;
cout << "Buffer Stack overflow. Cannot enter any more items";
}
}
if(*ptr == ')' || *ptr == '}' || *ptr == ']') {
//pop the item
bool result = expression.Pop(*ptr);
cout << "Popped Result: "<< result << endl;
if(result != 1) {
isValid = false;
}
}
ptr++;
}
cout << "isValid = " << isValid << endl;
if(isValid == 1 && expression.IsEmpty() == 1) {
cout << "valid expression!" << endl;
} else {
cout << "Invalid expression!" << endl;
}
}