2009-12-15 61 views
0

可能重複:
How to make YY_INPUT point to a string rather than stdin in Lex & Yacc (Solaris)如何從一個字符串,而不是一個文件解析

我想從一個字符串,而不是一個文件來分析。我知道v可以使用yy_scan_string fn來做到這一點。但對我來說,它不能正常工作,所以請幫助我

+1

發表一些代碼來說明您的問題。 – 2009-12-15 17:54:43

+0

YY_BUFFER_STATE my_string_buffer = yy_scan_string(my_string); yyparse(); yy_delete_buffer(my_string_buffer); 解析器錯誤在第一個標記處出現語法錯誤。我已經驗證了'my_string'的語法和內容通過文件使用 yyrestart(yyin)以及yy_create_buffer()。 – ajai 2009-12-15 18:26:01

+0

另請參閱:http://stackoverflow.com/q/1907847/15168。 – 2012-09-23 17:25:53

回答

5

我最近自己打過這個問題。有關該主題的flex文檔有點不盡人意。

我看到兩件事情可能會絆倒你。首先,注意你的字符串需要是雙NULL終止。也就是說,您需要採用一個常規的NULL結束字符串,並在其末尾添加ANOTHER NULL終止符。這個事實被埋在了flex文檔中,我花了一段時間才找到。

其次,你已經停止了對「yy_switch_to_buffer」的調用。這從文檔中也不是特別清楚。如果你改變你的代碼到這樣的東西,它應該工作。

// add the second NULL terminator 
int len = strlen(my_string); 
char *temp = new char[ len + 2 ]; 
strcpy(temp, my_string); 
temp[ len + 1 ] = 0; // The first NULL terminator is added by strcpy 

YY_BUFFER_STATE my_string_buffer = yy_scan_string(temp); 
yy_switch_to_buffer(my_string_buffer); // switch flex to the buffer we just created 
yyparse(); 
yy_delete_buffer(my_string_buffer); 
+0

不行不行。它表示YY_BUFFER_STATE未聲明 – ajai 2009-12-16 08:14:53

+0

(F)lex和Yacc/Bison經常在C中使用,在C++中使用較少。另外,你應該避免在同一個字符串上調用'strlen()'兩次。 – 2009-12-17 05:49:07

+0

是的,我意識到strlen問題......我想我應該花時間優化我的示例代碼。 ;) – 2009-12-17 06:01:04

相關問題