I can’t seem to figure out how to concatenate two string in yacc.
Here is the lex code
%{
#include <stdio.h>
#include "y.tab.h"
%}
%%
[0-9]+ {yylval.intval=atoi(yytext); return NR;}
[a-zA-Z]+ {yylval.strval=yytext; return STR;}
"0exit" {return 0;}
[ \t] ;
\n {return 0;}
. {return yytext[0];}
And here i have the basics to add two strings
%{
#include <stdio.h>
#include <string.h>
%}
%union {
int intval;
char* strval;
}
%token STR NR
%type <intval>NR
%type <strval>STR
%type <strval>operatie
%left '+' '-'
%right '='
%start S
%%
S : S operatie {}
| operatie {printf("%s\n",$<strval>$);}
;
operatie : STR '+' STR { char* s=malloc(sizeof(char)*(strlen($1)+strlen($3)+1));
strcpy(s,$1); strcat(s,$3);
$$=s;}
;
%%
int main(){
yyparse();
}
The code works, the problem is that the output is something like this:
If i input
aaaa + bbbb
i get the output
aaaa + bbbbbbbb
The problem is here:
yytext changes with every token and every buffer. Change it to