2016-02-27 57 views
1

我正在做一個簡單的編譯器,並且我使用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; 
} 

可能是什麼問題?

+1

標籤爲C++ 11:考慮'使用cstrset = unordered_set '而不是'typedef' – kfsone

回答

1

使用unordered_set<string>而不是您的unordered_set<const char*>。您試圖找到指向char數組的指針,該數組顯然不能存在於您定義的變量中。

+0

是的,這可能會工作,但使用const char *將幫助我稍後,所以我只會切換到字符串是不可能的。我不認爲這是指針問題。我嘗試了一個單獨的測試程序,而不使用flex,並且工作正常。我將編輯該問題以顯示此內容。 – devil0150

+0

爲什麼你更喜歡使用const char *?您可以隨時在字符串對象上使用.c_str()來提取此類型的值... –

+1

您的示例程序可能因爲編譯器優化而起作用 - 編譯器發現有兩個具有相同值的常量字符數組,因此它在每個用法中使用相同的指針... –