[請益] yacc與lex四則運算syntax error

作者: aa1727 (幫我加油好嗎)   2018-12-17 02:57:58
先附上程式碼:
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
搞整個週末了實在沒辦法只能求大神了

Links booklink

Contact Us: admin [ a t ] ucptt.com