如何获取flex和bison中token的字符串值?
我的 .lex 文件中有此标记:
[a-zA-Z0-9]+ { yylval = yytext; return ALPHANUM; }
并且 .y 文件中有此代码:
Sentence: "Sphere(" ALPHANUM ")."
{
FILE* file = fopen("C:/test.txt", "a+");
char st1[] = "polySphere -name ";
strcat(st1, $2);
strcat(st1, ";");
fprintf(file,"%s", st1);
fclose(file);
}
当我尝试编译时出现此错误:
警告:传递“strcat”的参数 2 使指针来自整数而不进行强制转换
所以 $2 是一个 int ,如何将其变成字符串?
例如:“球体(worldGlobe)。”我希望 $2 具有字符串值 worldGlobe 。
感谢您的帮助
I have this token in my .lex file:
[a-zA-Z0-9]+ { yylval = yytext; return ALPHANUM; }
and this code in my .y file:
Sentence: "Sphere(" ALPHANUM ")."
{
FILE* file = fopen("C:/test.txt", "a+");
char st1[] = "polySphere -name ";
strcat(st1, $2);
strcat(st1, ";");
fprintf(file,"%s", st1);
fclose(file);
}
I get this error when I try to compile:
warning: passing argument 2 of ‘strcat’ makes pointer from integer without a cast
So $2 is an int, how do I make it a string?
For example: "Sphere(worldGlobe)." I want $2 to have the string value worldGlobe here.
Thanks for any help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在没有
%union
声明的情况下,bison 将YYSTYPE
定义为 int,因此所有符号值是整数。
事实上,您对此问题有一些解决方案:
1) yylval|union 解决方案(推荐):
您可能知道 yylval 是词法分析器用来存储 yytext 变量的全局变量 (
yylval = yytext;
),因此您应该告诉词法分析器要存储哪些类型。您只需将此行添加到YACC 语法的标头:您将仅在此处存储字符串值。
顺便说一下,如果你想存储不同的类型,你应该在你的 yacc 文件中指定:
然后在你的 lex 中你将有
2) 使用 yytext:
建议:对于 yacc i 中的规则之后的回调,个人比较喜欢用函数。不是像您那样的整个代码:)
这个解决方案非常简单。
句子:“Sphere("{callback_your_function(yytext);} ALPHANUM ")."
这里的 yytext 将具有您的 ALPHANUM 令牌的值,因为它是下一个令牌。
In the absence of a
%union
declaration, bison definesYYSTYPE
to be int, so all of thesymbol values are integers.
In fact you have a few solutions for this problem:
1) yylval|union solution (RECOMMENDED):
As you may know yylval is a global variable used by the lexer to store yytext variable (
yylval = yytext;
) so you should tell your lexer which types you would to store.you can simply add this line to the header of your YACC grammar:you will store here only string values.
By the way if you want to store different types you should specify in your yacc file:
then in your lex you will have
2) Using yytext:
Advice: for callbacks after rules in yacc i,personally prefer to use functions. not the whole code as you do :)
this solution is really simple .
Sentence: "Sphere("{callback_your_function(yytext);} ALPHANUM ")."
the yytext here will have the value of your ALPHANUM token because it's the next token.