1

I'm trying to write a program that will tell me if all the tags in an HTML file are balanced, so every <tag> has a </tag>. I'm not worried about the self closing tags at this point. What I have I thought would work, but isn't quite right. It's looking at each element instead of looking for the open and closing tags as a whole. Can anyone tell me what I'm doing wrong?

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

I'm fairly new to C++ and especially stacks so please explain answers so that I might learn.

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

open [0]='<'およびcloseing[0]='<'なので、問題ありません。しかし、残念ながら、それは残りのキャラクターには当てはまりません。

open [1]='*'およびcloseing[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 に答える