1

我正在尝试编写一个程序,它会告诉我 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++ 非常陌生,尤其是堆栈,所以请解释答案,以便我学习。

4

1 回答 1

0

我发现了你的错误。你这样说:

 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] = '<' 和关闭[0] = '<' 所以没关系。但不幸的是,这不适用于其他角色:

打开[1] = '*' 和关闭[1] = '/'

不幸的是,即使我将代码更改为:

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

它仍然不起作用。我会进一步调查。

于 2012-07-19T00:33:04.177 回答