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

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

最佳答案

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

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

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

这应该是
if (nextChar() == '*')
{
    match('*');

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

关于c++ - 为什么我的程序无法正确读取消除的左递归语法规则? C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29158392/

10-11 22:42