我正在做一个简单的编译器,并且我使用flex和散列表(unordered_set
)来检查输入字是标识符还是关键字。Flex令牌不能使用char * hashtable
%{
#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;
}
我试图与只有写单词“类”的输入文件,输出是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:考虑'使用cstrset = unordered_set'而不是'typedef' –
kfsone