c++ - Flex token 不适用于 char* 哈希表

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

我正在制作一个简单的编译器,我使用 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;
}

可能是什么问题?

最佳答案

使用 unordered_set<string>而不是你的 unordered_set<const char*> .您正试图找到指向 char 数组的指针,而该指针显然不能存在于您定义的变量中。

关于c++ - Flex token 不适用于 char* 哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35673419/

相关文章:

vhdl - 如何编写不区分大小写的 Lex 模式规则?

c++ - 为没有继承的模板参数类提供构造函数

c++ - #define 导致 "Access violation reading location"

c++ - 插入顺序 std::map

c++11 - _mm_free 作为 unique_ptr 的删除器

c - 编译 lex 和 yacc 文件时出现大量错误

bison - YYSTYPE/YYLTYPE/yylval/yylloc 中的 S/L/l 代表什么?

c++ - 如何在 C++ 中将 unicode 字符转换为大写

c# - 驱动器号与 DevicePath

c++ - shared_ptr 成员和复制构造函数