【发布时间】: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 << "lex found an float: " << 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