繁体   English   中英

为什么我的程序无法正确读取消除的左递归语法规则? C ++

[英]Why is my program isn't reading eliminated left recursion grammar rules right? C++

它基于正则表达式编程,因此在详细介绍之前,这是我消除的左递归语法规则-

RE -> S RE2
RE2 -> S RE2
     | EMPTY

S -> E S2
S2 -> '|' E S2
    | EMPTY

E -> F E2
E2 -> '*' E2
    | EMPTY

F -> a
   | b
   | c
   | d
   | '('RE')'

好的,当我输入aababca|cab*等输入内容时,我的程序将无法读取多个字母。 你知道这是怎么回事吗?

#include <iostream>
#include <string>

using namespace std;

string input;
int index;

int nextChar();
void consume();
void match();
void RE();
void RE2();
void S();
void S2();
void E();
void E2();
void F();

int nextChar()
{
    return input[index];
}

void consume()
{
    index++;
}

void match(int c)
{
    if (c == nextChar())
        consume();
    else
        throw new exception("no");
}

void RE()
{
    S();
    RE2();
}

void RE2()
{
    if (nextChar() == 'a' || nextChar() == 'b' || nextChar() == 'c' || nextChar() == 'd' || nextChar() == '|' || nextChar() == '*' || nextChar() == '(' || nextChar() == ')')
    {
        S();
        RE2();
    }
    else
        ;
}

void S()
{
    E();
    S2();
}

void S2()
{
    if (nextChar() == 'a' || nextChar() == 'b' || nextChar() == 'c' || nextChar() == 'd' || nextChar() == '|' || nextChar() == '*' || nextChar() == '(' || nextChar() == ')')
    {
        match('|');
        E();
        S2();
    }
    else
        ;
}

void E()
{
    F();
    E2();
}

void E2()
{
    if (nextChar() == 'a' || nextChar() == 'b' || nextChar() == 'c' || nextChar() == 'd' || nextChar() == '|' || nextChar() == '*' || nextChar() == '(' || nextChar() == ')')
    {
        match('*');
        E2();
    }
    else
        ;
}

void F()
{
    if (nextChar() == 'a')
    {
        match('a');
    }
    else if (nextChar() == 'b')
    {
        match('b');
    }
    else if (nextChar() == 'c')
    {
        match('c');
    }
    else if (nextChar() == 'd')
    {
        match('d');
    }
    else if (nextChar() == ('(' && ')'))
    {
        match('(');
        RE();
        match(')');
    }
}

int main()
{
    cout << "Please enter a regular expression: ";
    getline(cin, input);

    input = input + "$";
    index = 0;

    try
    {
        RE();
        match('$');

        cout << endl;
        cout << "** Yes, this input is a valid regular expression. **";
        cout << endl << endl;
    }
    catch (...)
    {
        cout << endl;
        cout << "** Sorry, this input isn't a valid regular expession. **";
        cout << endl << endl;
    }

    return 0;
}

我强烈建议学习如何使用调试器。 然后,您可以逐行浏览并查看您的程序在做什么,甚至可以在throw调用上放置一个断点并查看堆栈跟踪。

在这种情况下,您的E2中的if测试会检查很多字符,如果不是* ,则会引发错误。

if (nextChar() == 'a' || nextChar() == 'b' || nextChar() == 'c' || nextChar() == 'd' || nextChar() == '|' || nextChar() == '*' || nextChar() == '(' || nextChar() == ')')
{
    match('*');

这应该是

if (nextChar() == '*')
{
    match('*');

您的代码中多次出现此问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM