如何从字符串而不是文件解析

aja*_*jai 0 yacc lex flex-lexer

可能重复:
如何使YY_INPUT指向Lex&Yacc(Solaris)中的字符串而不是stdin

我想从字符串而不是文件解析.我知道v可以使用yy_scan_string fn来做它.但对我来说它不能正常工作所以请帮助我

Rus*_*ist 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 );
Run Code Online (Sandbox Code Playgroud)