作者aa1727 (Sean)
看板Programming
标题[请益] yacc与lex 四则运算
时间Mon Dec 17 02:57:58 2018
先附上程式码:
Lex:
%{
#include <stdio.h>
#include "y.tab.h"
%}
%option noyywrap
%%
[0-9]+ { yylval = atoi(yytext); return INTEGER; }
[\+\-\*\/\(\)\n] { return *yytext; }
[\t] {}
. { yyerror("invalid char."); }
%%
Yacc:
%{
#include <stdio.h>
#include <stdlib.h>
#include "y.tab.h"
int yylex();
%}
%token INTEGER
%left '+' '-'
%left '*' '/'
%nonassoc UMINUS
%%
program:
|program expression '\n' { printf("Ans : %d\n\n", $2); }
;
expression :
INTEGER { $$ = $1; }
| expression '+' expression { $$ = $1 + $3;
printf("%d + %d = %d \n",$1,$3,$$);}
| expression '-' expression { $$ = $1 - $3;
printf("%d - %d = %d \n",$1,$3,$$);}
| expression '*' expression { $$ = $1 * $3;
printf("%d * %d = %d \n",$1,$3,$$);}
| expression '/' expression { $$ = $1 / $3;
printf("%d / %d = %d \n",$1,$3,$$);}
| '-' expression %prec UMINUS { $$ = -$2; }
| '(' expression ')' { $$ = $2; }
| { yyerror("invalid input.\n"); }
;
%%
int main()
{
yyparse();
return 0;
}
void yyerror(char *msg)
{
printf("Error: %s \n",msg);
}
要实现 +-*/()和负数四则运算
不知道为什麽最後会出现
syntax error
https://i.imgur.com/PkahB5J.jpg
搞整个周末了实在没办法只能求大神了
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 39.10.237.189
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Programming/M.1544986680.A.BAF.html
※ 编辑: aa1727 (39.10.237.189), 12/17/2018 02:59:02
1F:推 CindyLinz: 你 program 没有可以结束的 rule 啊 112.121.78.5 12/17 14:29