Mex
Mex

Reputation: 1

YACC/LEX yyparse() in loop Issue

I'm trying to parse an input in a loop until user enter "quit". However, When I pass the query through a parameter, the yyparse() works but when I doing the same process in the loop, it shows the error.

I already checked 'cmd' and it shows the exact entered user's query.

int main(int argc, char* argv[]) {
    string cmd;
    string terminate = ".q";
    do
    {
        cout << endl << "Enter Query>";
        std::getline(std::cin, cmd);
        int parse = -1;
        if (yyparse() == 0) {
            cout << "OK!" << endl;
            parse = 0;
        }
        else {
            cout << "Error!" << endl;
            parse = -1;
            //continue;
        }
    } while (cmd != terminate);

Upvotes: 0

Views: 712

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126418

This is mostly a lex issue, not a yacc issue.

By default, a lex lexer will read from stdin, until EOF is reached. Once you get to EOF you're done -- all further reads from stdin and calls to yylex return EOF.

If you want to read from somewhere else (such as a string), you need to do something else. Flex provides yy_scan_string to read from a string, and if you use that, yylex calls return EOF when you get to the end of the string, at which point you can call yy_scan_string again to read from another string. So something like:

do
{
    cout << endl << "Enter Query>";
    std::getline(std::cin, cmd);
    YY_BUFFER_STATE buf = yy_scan_string(cmd.c_str());
    int parse = -1;
    if (yyparse() == 0) {...

    yy_delete_buffer(buf);

Upvotes: 1

Related Questions