我正在尝试编写一个程序,它会告诉我 HTML 文件中的所有标签是否都是平衡的,所以每个标签<tag>
都有一个</tag>
. 在这一点上,我并不担心自闭标签。我认为我认为会起作用,但并不完全正确。它正在查看每个元素,而不是作为一个整体寻找打开和关闭标签。谁能告诉我我做错了什么?
const string opening = "<*>";
const string closing = "</*>";
string input;
int main()
{
char element;
stack<char> stk;
ifstream file;
cout << "Please Enter File name: ";
cin >> input;
//std::file.open(input);
file.open(input.c_str());
if(file.fail())
cout<<"File is corrupt or does not exists!"<<endl;
while(!file.eof())
{
file>>element;
//push left group symbols onto stack
if(element==opening[0])
stk.push(element);
else if(element==opening[1])
stk.push(element);
else if(element==opening[2])
stk.push(element);
}
file.close();
file.open(input.c_str());
while(!file.eof())
{
file>>element;
if(stk.top()==opening[0])
{
if(element==closing[0])
stk.pop();
}
else if(stk.top()==opening[1])
{
if(element==closing[1])
stk.pop();
}
else if(stk.top()==opening[2])
{
if(element==closing[2])
stk.pop();
}
}
file.close();
if(!stk.empty())
cout<<"\nILLEGAL"<<endl;
else if(stk.empty())
cout<<"\nLEGAL"<<endl;
cout << "\n\nProgram complete." << endl;
return 0;
}
我对 C++ 非常陌生,尤其是堆栈,所以请解释答案,以便我学习。