可能重复:
How to make YY_INPUT point to a string rather than stdin in Lex & Yacc (Solaris)
我想从字符串而不是文件解析。我知道v可以使用yy_scan_string fn来做它。但对我来说它不能正常工作所以请帮助我
答案 0 :(得分: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 );