I have to write a program to check for balanced tags in a HTML code. I have written the code below so far but it is not working right it was brought to my attention that my coding is wrong and that it needs to be fixed.
Code:
while (pos != string::npos)
{
if (pos=str.find("<" && ">",pos+1))
push(&stack, 1);
}
while (pos1 != string::npos)
{
if (pos1=str.find("</" && ">",pos1+1))
pop(&stack);
}
This is the part where my code is wrong I was told that you can not do string find the way i have it done here. What i want it to do but cant seem to figure out is when it sees <...> pushp and then when it sees a </...> pop. So i need help on the right way to write this portion of code. Thanks in advance.
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
#define MAX 300
//My stack Structure that i used i can handle integers.
typedef struct stack
{
int item[MAX];
int Top;
}STACK;
void push(STACK *ps, int x)
{
if (ps->Top == MAX) {
fputs("Error: stack overflow\n", stderr);
abort();
} else
ps->item[ps->Top++] = x;
}
int pop(STACK *ps)
{
if (ps->Top == 0){
fputs("Error: stack underflow\n", stderr);
abort();
} else
return ps->item[--ps->Top];
}
int main ()
{
//File input and string declaring
size_t pos1;
size_t pos;
string str, tmp;
std::string filename;
cout <<"Please enter the name of the file" << endl;
cin >> filename;
ifstream myfile(filename.c_str());
while(getline(myfile, tmp))
{
str += tmp;
}
//Stack declaring
STACK stack;
stack.Top = 0;
pos1= 0;
pos = 0;
// This below code is were my problem is I understand
// That you cant use find the way i am doing it and
// would like some help with the right way.
while (pos != string::npos)
{
if (pos=str.find("<" && ">",pos+1))
push(&stack, 1);
}
while (pos1 != string::npos)
{
if (pos1=str.find("</" && ">",pos1+1))
pop(&stack);
}
//Checking if stack is full or empty. If stack is empty
// The code is balanced otherwise it is not.
if (stack.Top == 0)
{
cout << "Legal" << endl;
}
else
{
cout << "Illegal" << endl;
}
system("pause>nul");
return 0;
}
Thanks again for any help in advance