【问题标题】:Flex tokens not working with char* hashtableFlex 令牌不适用于 char* 哈希表
【发布时间】:2016-02-27 18:04:28
【问题描述】:

我正在制作一个简单的编译器,我使用 flex 和哈希表 (unordered_set) 来检查输入的单词是标识符还是关键字。

%{
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unordered_set>
using std::unordered_set;
void yyerror(char*);
int yyparse(void);

typedef unordered_set<const char*> cstrset;
const cstrset keywords = {"and", "bool", "class"};
%}
%%
[ \t\n\r\f]             ;
[a-z][a-zA-Z0-9_]*      {   if (keywords.count(yytext) > 0)
                                printf("%s", yytext);
                            else
                                printf("object-identifier"); };

%%

void yyerror(char* str) {printf("ERROR: Could not parse!\n");}
int yywrap() {}

int main(int argc, char** argv)
{
    if (argc != 2) {printf("no input file");}
    FILE* file = fopen(argv[1], "r");
    if (file == NULL) {printf("couldn't open file");}
    yyin = file;
    yylex();
    fclose(file);
    return 0;
}

我尝试使用只写有单词“class”的输入文件,输出是object_identifier,而不是class

我尝试了一个简单的程序,没有使用 flex,unordered_set 工作正常。

int main()
{
    cstrset keywords = {"and", "class"};
    const char* str = "class";
    if (keywords.count(str) > 0)
        printf("works");
    return 0;
}

可能是什么问题?

【问题讨论】:

  • 标记的 C++11:考虑 using cstrset = unordered_set&lt;const char*&gt; 而不是 typedef

标签: c++ c++11 flex-lexer unordered-set


【解决方案1】:

使用unordered_set&lt;string&gt; 而不是您的unordered_set&lt;const char*&gt;。您正试图找到指向显然不能存在于您定义的变量中的 char 数组的指针。

【讨论】:

  • 是的,这可能行得通,但使用 const char* 稍后会帮助我,所以只有在不可能的情况下我才会切换到字符串。而且我不认为这是指针问题。我在不使用 flex 的情况下尝试了一个单独的测试程序,并且成功了。我将编辑问题以显示这一点。
  • 为什么更喜欢使用 const char *?您始终可以在字符串对象上使用 .c_str() 来提取此类值...
  • 您的示例程序可能由于编译器优化而工作——编译器看到有两个具有相同值的 const char 数组,因此它在每次使用时使用相同的指针...
  • 我真正的意思是,如果我现在开始使用字符串,我可能需要更改很多代码。
  • 好的,我明白了...您可以尝试为 const char * 创建自己的哈希函数,以使您的 unordered_set 按预期工作。见:stackoverflow.com/questions/20649864/…
猜你喜欢
  • 2014-11-21
  • 2019-05-02
  • 2013-03-20
  • 2020-02-16
  • 2012-03-01
  • 2016-01-28
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
相关资源
最近更新 更多