【问题标题】:No ouput from lexer in lex and yacclex 和 yacc 中的 lexer 没有输出
【发布时间】:2014-04-29 18:47:30
【问题描述】:

我在使用 lex 和 yacc 时观察到一种奇怪的行为。

这是我的 lex 文件 -- ex.l

%option noyywrap
%option yylineno
%{
#include <iostream>
using namespace std; 

#include "y.tab.h" 
 
void yyerror(char *);  // to get the token types that we return
%}

%%
[ \t] ;

[0-9]+\.[0-9]+ { yylval.fval = atof(yytext); //this is not working 
                 cout << "lex found an float: "; return FLOATS; }
[0-9]+  { cout << "lex found an int: "; yylval.ival = atoi(yytext); return INTS; }
[a-zA-Z0-9]+ {
     
    char *res = new char[strlen(yytext) + 1];
    strcpy(res, yytext);
    yylval.sval = res;
    return STRINGS;
}

. ;

%%

hHre 是我的 yacc 文件 -- ex.y

%{
#include <iostream>
using namespace std ; 

extern int yylex();
extern int yyparse();
extern FILE *yyin;
extern int yynerrs; 
extern void yyerror(char *s);
%}

%union {
    int ival;
    float fval;
    char *sval;
}

%token <ival> INTS
%token <fval> FLOATS
%token <sval> STRINGS

%%

grammar:
    INTS grammar { cout << "yacc found an int: " << $1 << endl; }
    | FLOATS grammar { cout << "yacc found a float: " << $1 << endl; }
    | STRINGS grammar { cout << "yacc found a string: " << $1 << endl; }
    | INTS { cout << "yacc found an int: " << $1 << endl; }
    | FLOATS { cout << "yacc found a float: " << $1 << endl; }
    | STRINGS { cout << "yacc found a string: " << $1 << endl; }
    ;
%%
#include <stdio.h>

 
main() {
     yyin = stdin;
    do {
    yyparse();
    } while (!feof(yyin));
    
}

void yyerror(char *s) {
    cout << "EEK, parse error!  Message: " << s << endl;
    exit(-1);
}

编译这两个并运行它们后,我没有从 lex for ex 中得到输出:-

为什么会这样?为什么 cout 语句在 lex 的作用下不起作用?

【问题讨论】:

  • 据我所知,您没有输入任何浮点数。 ;)
  • 您在 ex.l 中的 cout 语句后面没有任何值 - 如果您输入 cout &lt;&lt; "lex found an float: " &lt;&lt; yylval.fval,那么它将起作用。
  • @codebeard:为什么会这样???现在它的工作??
  • 我不是 100% 清楚你希望看到什么输出......我得到的原始代码是:./a.out / 34 / lex found an int: / 56 / lex found an int: / 78 / lex found an int: / yacc found an int: 78 / yacc found an int: 56 / yacc found an int: 34
  • 在我做出改变之前它对我有用。

标签: c++ token flex-lexer lex


【解决方案1】:

问题是我认为ex.y中的以下代码。

%token <ival> INTS
%token <fval> FLOATS
%token <sval> STRINGS

使用内置令牌。这会覆盖 ex.l 文件中定义的标记。从某种意义上说,执行永远不会到达 ex.l 文件中的 cout 行。

尝试只编写以下代码,它应该可以工作。

%token INTS
%token FLOATS
%token STRINGS

希望这会有所帮助。

注意:我没有测试过代码。因此,您在执行此操作后可能会遇到其他错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    相关资源
    最近更新 更多