问题描述
我想从字符串而不是文件中进行解析.我知道v可以使用yy_scan_string fn来做到这一点.但是对我来说,它不能正常工作,所以请帮助我
i want to parse from a string rather than a file. i know that v can use yy_scan_string fn to do it.but for me it's not working properly so pls help me
推荐答案
我最近亲自解决了这个问题.关于该主题的flex文档还有一些不足之处.
I fought through this problem myself very recently. The flex documentation on the subject leaves a bit to be desired.
我马上发现有两件事可能会绊倒你.首先,请注意,您的字符串需要双NULL终止.也就是说,您需要获取一个以NULL终止的常规字符串,并在其末尾添加另一个NULL终止符.这个事实被隐藏在flex文档中,我花了一段时间才找到它.
I see two things right off the bat that might be tripping you up. First, note that your string needs to be double NULL terminated. That is, you need to take a regular, NULL terminated string and add ANOTHER NULL terminator at the end of it. That fact is buried in the flex documentation, and it took me a while to find as well.
第二,您取消了对"yy_switch_to_buffer"的调用.从文档中也不清楚这一点.如果将代码更改为类似的代码,它应该可以工作.
Second, you've left off a call to "yy_switch_to_buffer". This is also not particularly clear from the documentation. If you change your code to something like this, it should work.
// 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 );
这篇关于如何从字符串而不是文件中解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!