如何获取flex和bison中token的字符串值?

发布于 2024-12-22 20:48:00 字数 508 浏览 4 评论 0原文

我的 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

简单爱 2024-12-29 20:48:00

在没有 %union 声明的情况下,bison 将 YYSTYPE 定义为 int,因此所有
符号值是整数。
事实上,您对此问题有一些解决方案:

1) yylval|union 解决方案(推荐):
您可能知道 yylval 是词法分析器用来存储 yytext 变量的全局变量 (yylval = yytext;),因此您应该告诉词法分析器要存储哪些类型。您只需将此行添加到YACC 语法的标头:

#define YYSTYPE char *

您将仅在此处存储字符串值。

顺便说一下,如果你想存储不同的类型,你应该在你的 yacc 文件中指定:

%union {
    char *a;
    double d;
    int fn;
}

然后在你的 lex 中你将有

[a-zA-Z0-9]+    { **yylval.a** = yytext; return ALPHANUM; }

2) 使用 yytext:

建议:对于 yacc i 中的规则之后的回调,个人比较喜欢用函数。不是像您那样的整个代码:)

这个解决方案非常简单。
句子:“Sphere("{callback_your_function(yytext);} ALPHANUM ")."

这里的 yytext 将具有您的 ALPHANUM 令牌的值,因为它是下一个令牌。

In the absence of a %union declaration, bison defines YYSTYPE to be int, so all of the
symbol 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:

#define YYSTYPE char *

you will store here only string values.

By the way if you want to store different types you should specify in your yacc file:

%union {
    char *a;
    double d;
    int fn;
}

then in your lex you will have

[a-zA-Z0-9]+    { **yylval.a** = yytext; return ALPHANUM; }

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文