为什么我的程序没有读取被删除的左递归语法规则呢? C ++

时间:2015-03-20 02:29:17

标签: c++ regex

它基于正则表达式编程,所以在我查看详细信息之前,这里是我的消除左递归语法规则 -

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*等输入时,我的节目赢了&#39 ; t能够读取多个字母。你知道这个是什么吗?

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

1 个答案:

答案 0 :(得分:1)

我强烈建议您学习如何使用调试器。然后,您可以逐行逐步查看程序正在执行的操作,甚至在throw调用上设置断点并查看堆栈跟踪。

在这种情况下,您在E2中的if测试会检查大量字符,如果不是*,则会抛出错误。

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

这应该只是

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

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