문제

I'm trying to Parse a Fully Parenthesized Exp for this grammar:

exp->(exp + exp)
    |(exp - exp)
    | num
num->[0-9]

...but I have a problem: when I enter "1+4" no error appears. How can I solve it ??

도움이 되었습니까?

해결책

This is a classic problem of recursive descent parsers: your grammar does not require that the entire input is consumed. Once it finishes with the "while isdigit" loop, it considers its job done, ignoring the +4 portion of the input.

Add a check that the end of line is reached after the call of the top-level expression to address this problem:

void TopExp() {
    Expr();
    Match('\n');
}

You need to modify Match to allow matching \n when no additional input is available:

void Match(char c) {
    int p = cin.peek();
    if(p==c) {
        cin>>c;
    } else if (p == EOF && c == '\n') {
        return
    } else {
        cout<<"Syntax Error! "<<(char)cin.peek()<<endl;
        cin.ignore();
    }
}

다른 팁

Try with this changed instruction: if (openParenthesis-closeParenthesis>0)

    int Match(char c)
    {
        if(cin.peek()==c) {
            cin>>c;
            return 1;
        } else
        {
            cout<<"Syntax Error! "<<(char)cin.peek()<<endl;
            cin.ignore();
            return 0;
        }
    }

    void MatchOp()
    {
        if(cin.peek()=='+') 
            Match('+');
        else if(cin.peek()=='-')
            Match('-');
        else
        {
            cout<<"invalid Operation: "<<(char)cin.peek()<<endl;
            cin.ignore();
        }
    }

    void Exp()
    {   static int openParenthesis = 0; 
        static int closeParenthesis = 0;  
        if(cin.peek()!='\n')
            if(cin.peek()=='(')
            {
                if (Match('(') == 1) {
                    openParenthesis += 1;
                }
                Exp();MatchOp();Exp();
                if (Match(')') == 1) {
                    closeParenthesis -= 1;
                }
            }
            else if(isdigit(cin.peek()))
            {   
                if (openParenthesis-closeParenthesis>0) {
                    cout<<"Syntax Error! "<<(char)cin.peek()<<endl;
                    cin.ignore();               
                } else {
                    while(isdigit(cin.peek()))
                    { cout<<(char)cin.peek();
                    Match(cin.peek());  
                    }
                }   
            }
            else 
            {
                cout<<"Syntax Error!"<<(char)cin.peek()<<endl;
                cin.ignore();
            }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top