I need to make use of my own stack implementation to check any HTML source file
ID: 3737145 • Letter: I
Question
I need to make use of my own stack implementation to check any HTML source file for balanced tags. I have to write in my C++ program below that reads the strings of symbols from a HTML source file (et.html) and print "legal or "illegal" as the result.
#include<bits/stdc++.h>
#define MAX 1000
using namespace std;
class Stack{
int top;
public:
int a[MAX]; // Max size of Stack
Stack(){
top = -1;
}
//top is initialized to -1 to check the emptiness of the stack
bool push(int x);
int pop();
bool isEmpty();
int peek();
};
int Stack::peek(){
return a[top];
}
bool Stack::push(int x){
if (top >= MAX){
cout << "Stack is full it is Overflowing";
return false;
}
else{
a[++top] = x;
return true;
}
}
int Stack::pop(){
if (top < 0)
return 0;
else{
int x = a[top--];
return x;
}
}
//Checks the stack if its empty or not
bool Stack::isEmpty(){
return (top < 0);
}
// checks for pairs
bool Pair(char opening,char closing){
if(opening == '(' && closing == ')') return true;
else if(opening == '{' && closing == '}') return true;
else if(opening == '[' && closing == ']') return true;
return false;
}
bool Balanced(string exp){
Stack S;
for(int i =0;i<exp.length();i++){
if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
S.push(exp[i]);
else if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']'){
if(S.isEmpty() || !Pair(S.peek(),exp[i]))
return false;
else
S.pop();
}
}
return S.isEmpty() ? true:false;
}
int main(){
string expression; // input expression
ifstream in("program.c");
if(in.is_open()) {
expression = "";
string line;
while(getline(in, line)) {
expression += line+" ";
}
}
else {
cout << "failed to open file" << endl;
return 0;
}
// check expression
if (Balanced(expression))
cout << "Legal ";
else
cout << "Illegal ";
return 0;
}
Explanation / Answer
I think the code what you have pasted here is not actually checking html tag is balance or not. Fir you need to understand here tags in html. I am giving you a very basic example of html tags in an html file. Main root tag is <html</html> in this tag all tags will come But you are checking here parenthesis i.e [{()}].Please follow below html tags in your code. I hope this will help you.
<html>
<head></head>
<body>
</body>
</html>