Using FLEX to scan a string instead of a file or console input.
Posted In:
FLEX
.
By Sid
Problem:
The current problem I'm working on is how to make the lexical analyzer generated by FLEX analyze the contents of a string and not a file or console input.
Normally what you do is if you want FLEX to analuze the contents of the console input you assign the varibale yyin to stdin or for a file a file pointer.
yyin = stdin;
yyin = fopen("filename","attribute r/w/r+/w+/a");
Now, according to this manual, you can use the function yy_scan_string(char *) to scan the contents of a string. Actually, a copy of the contents of a string would be more accurate since the string contents are put in a buffer, which is modified, so this function's default implementation is to copy the contents.
URL: FLEX Manual describging yy_scan_string
Solution:
We use yy_scan_string(char *statement)
NOTE: The input string that you pass has to be a NULL terminated string.
char *input = "This is my input string.\0"
yy_scan_string(input);
So the usage is as follows:
/*Copy string into new buffer and Switch buffers*/
yy_scan_string (input);
/*Analyze the string*/
yylex();
/*Delete the new buffer*/
yy_delete_buffer(YY_CURRENT_BUFFER);
4 Responses to Using FLEX to scan a string instead of a file or console input.
Just what I was looking for. Thanks for the nice and precise post.
But where to put this code?
Thanks for this. I have been trying to do this without success until I read your blog
Wanted to know; what if you wanted to update values from the string to a data structure?
Something to say?