如何获取flex和bison中token的字符串值? [英] How to get string value of token in flex and bison?

查看:406
本文介绍了如何获取flex和bison中token的字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的.lex文件中有此令牌:

I have this token in my .lex file:

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

,并将此代码保存在我的.y文件中:

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:

警告:传递"strcat"的参数2会使指针从整数开始而无需强制转换

warning: passing argument 2 of ‘strcat’ makes pointer from integer without a cast

因此,$ 2是一个整数,如何将其设为字符串?

So $2 is an int, how do I make it a string?

例如:"Sphere(worldGlobe)".我希望$ 2在这里具有字符串值worldGlobe.

For example: "Sphere(worldGlobe)." I want $2 to have the string value worldGlobe here.

感谢您的帮助

推荐答案

在没有%union声明的情况下,野牛将YYSTYPE定义为int,因此所有 符号值是整数. 实际上,您有一些解决此问题的方法:

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解决方案(推荐):
您可能知道yylval是词法分析器用来存储yytext变量(yylval = yytext;)的全局变量,因此您应该告诉词法分析器要存储哪种类型.您只需将以下行添加到YACC语法的标题中即可:/p>

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.

如果要存储其他类型,应在yacc文件中指定:

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

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

然后您将在lex中拥有

then in your lex you will have

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

2)使用yytext:

建议:对于yacc i中的规则后的回调,个人更喜欢使用函数.并非像您所做的那样是整个代码:)

Advice: for callbacks after rules in yacc i,personally prefer to use functions. not the whole code as you do :)

此解决方案非常简单.
Sentence: "Sphere("{callback_your_function(yytext);} ALPHANUM ")."

this solution is really simple .
Sentence: "Sphere("{callback_your_function(yytext);} ALPHANUM ")."

此处的 yytext 具有您的ALPHANUM令牌的值,因为它是下一个令牌.

the yytext here will have the value of your ALPHANUM token because it's the next token.

这篇关于如何获取flex和bison中token的字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆