C++ 使用堆栈检查HTML标记的平衡

C++ 使用堆栈检查HTML标记的平衡,c++,stack,C++,Stack,我正在尝试编写一个程序,告诉我HTML文件中的所有标记是否都是平衡的,因此每个标记都有一个。我现在不担心自动关闭标签。我所拥有的我认为会有用,但并不完全正确。它查看每个元素,而不是作为一个整体查看打开和关闭标记。谁能告诉我我做错了什么 const string opening = "<*>"; const string closing = "</*>"; string input; int main() { char element; stack&l

我正在尝试编写一个程序,告诉我HTML文件中的所有标记是否都是平衡的,因此每个标记都有一个。我现在不担心自动关闭标签。我所拥有的我认为会有用,但并不完全正确。它查看每个元素,而不是作为一个整体查看打开和关闭标记。谁能告诉我我做错了什么

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++非常熟悉,尤其是堆栈,所以请解释答案,以便我能学习。 我发现了你的错误。你这样说:

 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();
    }

打开[0]=“文件中的标记是否由和组成?另外,记住,拥有像.while这样的东西是合法的!file.eof file>>元素;最好替换为while file>>元素。请参阅,以获取对此的解释。我已经对此进行了一些测试。我使用了一个包含以下内容的文件:我发现由于某种原因,当重新读取该文件时,它会将最后一个字符读取两次。@chris否该文件不是由和组成的。我以为有了*会认为那里什么都有可能。我需要像和这样的东西吗?而且,我意识到这是合法的,但是对于这个案子我不需要担心。谢谢你的。eof提示@克里斯,我不要成品。我正试图用我拥有的一本书来学习C++,它让我编写了一个堆栈来检查文本文件中{{}[]的平衡,我做到了。所以我决定试着检查html标记,但这比我最初认为的更具挑战性。我将尝试更改我的代码以使用find或substr。我知道它是在查看单个字符,但我想我需要它来找到开头,然后按下。一旦找到了相应的字符,就会弹出。我的观点是,你的字符不匹配。如果你忽略了两者之间的一切,那么你就不知道你是否遇到了正确的对应关系
 if(stk.top()==opening[0])
    {
        if(element==closing[0])
            stk.pop();
    }
    else if(stk.top()==opening[1])
    {
        if(element==closing[2])
            stk.pop();
    }
    else if(stk.top()==opening[2])
    {
        if(element==closing[3])
            stk.pop();
    }