Flex 和 Bison 不识别字符
Flex and Bison does not recognize character
我想制作一个简单的计算器来计算 3+4 或 5/8 的值,但我对使用数学函数的 abs 有疑问。我的代码如下:
野牛文件:
%{
#include <stdio.h>
#include <math.h>
%}
/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist: /* nothing */
| calclist exp EOL {
printf("= %d\n", );
}
;
exp: factor
| exp ADD factor { $$ = + ; }
| exp SUB factor { $$ = - ; }
;
factor: term
| factor MUL term { $$ = * ; }
| factor DIV term { $$ = / ; }
;
term: NUMBER
| ABS term {$$=fabs()}
;
%%
main(int argc, char **argv)
{
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
}
和 Flex 文件
%{
# include "calc.tab.h"
%}
/* recognize tokens for the calculator and print them out */
%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"@" { return ABS; }
[0-9]+ { yylval = atoi(yytext);
return NUMBER;
}
\n { return EOL; }
[ \t] { /* ignore whitespace */ }
. {
printf("Mystery character %c\n", *yytext);
}
%%
yywrap()
{
}
我为绝对值选择了 @ 符号,但我的程序确实识别如下表达式:
4+@5,但不像 4+@-5
我应该在我的程序中更改什么才能识别此运算符?
看来@
运算符定义是正确的。但是,您的语言定义不接受一元减号,即您的代码不能接受 4+-5
之类的东西而没有 @
。您需要添加适当的语言定义以支持一元负号。 (如果你需要,一元加)。有关一元运算符的详细信息,以及它们与二元运算符的不同之处,您可以阅读 Unary Operation on wiki.
您可以尝试类似的方法:
term: NUMBER
| ABS term {$$ = fabs(); }
| SUB term {$$ = -; }
;
我想制作一个简单的计算器来计算 3+4 或 5/8 的值,但我对使用数学函数的 abs 有疑问。我的代码如下:
野牛文件:
%{
#include <stdio.h>
#include <math.h>
%}
/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist: /* nothing */
| calclist exp EOL {
printf("= %d\n", );
}
;
exp: factor
| exp ADD factor { $$ = + ; }
| exp SUB factor { $$ = - ; }
;
factor: term
| factor MUL term { $$ = * ; }
| factor DIV term { $$ = / ; }
;
term: NUMBER
| ABS term {$$=fabs()}
;
%%
main(int argc, char **argv)
{
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
}
和 Flex 文件
%{
# include "calc.tab.h"
%}
/* recognize tokens for the calculator and print them out */
%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"@" { return ABS; }
[0-9]+ { yylval = atoi(yytext);
return NUMBER;
}
\n { return EOL; }
[ \t] { /* ignore whitespace */ }
. {
printf("Mystery character %c\n", *yytext);
}
%%
yywrap()
{
}
我为绝对值选择了 @ 符号,但我的程序确实识别如下表达式:
4+@5,但不像 4+@-5
我应该在我的程序中更改什么才能识别此运算符?
看来@
运算符定义是正确的。但是,您的语言定义不接受一元减号,即您的代码不能接受 4+-5
之类的东西而没有 @
。您需要添加适当的语言定义以支持一元负号。 (如果你需要,一元加)。有关一元运算符的详细信息,以及它们与二元运算符的不同之处,您可以阅读 Unary Operation on wiki.
您可以尝试类似的方法:
term: NUMBER
| ABS term {$$ = fabs(); }
| SUB term {$$ = -; }
;