ERROR while doing integer printf When I try to enter the text: WRITE 10; FINISH; the segmentation fault (core image saved) error appears, since the list is a string type and I can not do integer printf.
Follow the YACC / BISON code:
%{
#include <stdio.h>
int yylex(void);
int yyerror(const char *s);
char stR[20];
%}
%union{
char *str; /* para strings*/
int num; /* para inteiros */
}
%token TERMINAR ESCREVER
%token SUBTRACAO
%token MULTIPLICACAO
%token DIVISAO
%token SOMA
%token<num> NUM
%token<str> TEXTO
%type<str> elemento
%type<num> expr
%type<str> lista
%start s
%%
s:linha s
|TERMINAR ';' {return 0;}
;
linha: ESCREVER lista ';' {printf("%s",$2);}
| VARS
;
lista: elemento { $$=$1; }
|lista ',' elemento
;
elemento:TEXTO { $$=$1; }
|expr
;
VARS :
| NUM
| TEXTO
| expr
| TEXTO '=' VARS ';' /* para delcaracoes */
;
expr : NUM SOMA expr {$$=$1+$3;}
| NUM SUBTRACAO expr {$$=$1-$3;}
| NUM MULTIPLICACAO expr {$$=$1*$3;}
| NUM DIVISAO expr {$$=$1/$3;}
| NUM '+' expr {$$=$1+$3;}
| NUM '=' expr {$$=$1=$3;}
| NUM '-' expr {$$=$1-$3;}
| NUM '*' expr {$$=$1*$3;}
| NUM '/' expr {$$=$1/$3;}
| NUM {$$=$1; }
;
%%
LEX Code
%{
#include <stdio.h>
#include <stdlib.h>
#include "gram.h"
int yyerror(const char *s);
%}
%%
"ESCREVER" {return ESCREVER; }
"TERMINAR" {return TERMINAR; }
[0-9]+ { yylval.num =atoi(yytext);
return NUM; }
[A-Za-z0-9]* { yylval.str=strdup(yytext);
return TEXTO;}
"/" |
"-" |
"+" |
"*" |
"=" |
"." |
";" |
"," {return yytext[0]; }
[ \n\t] { }
. { return yytext[0]; }
%%
int yywrap(){ return 1; }