yacc で 2 つの文字列を連結する方法がわかりません。
レックスコードはこちら
%{
#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];}
そして、ここに2つの文字列を追加するための基本があります
%{
#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();
}
コードは機能します。問題は、出力が次のようになることです。
あああ+bbbb
私は出力を得る
あああ+bbbbbbbb