我有一个 Lex 程序,可以读取给定字符是字母还是数字。如何直接从文件中获取输入。这是我的简单程序。还有什么是 Flex/Lex 的好教程
%{
#include<stdio.h>
%}
%%
[a-zA-Z]+ printf("Token Type: STRINGLITERAL \n Value: [%s] ",yytext);
[0-9]+ printf("Token Type: INTLITERAL \n VALUE:[%s]", yytext);
. printf("[%s] is not a word",yytext);
%%
int main(void)
{
yylex();
return 0;
}
最佳答案
我喜欢 flex 的 C++ 输出。
词法分析器.l
%option c++
%{
#include <string>
#include <iostream>
%}
WhiteSpace [ \t]
%%
[A-Za-z]+ {std::cout << "WORD: " << std::string(yytext, yyleng) << "\n"; return 1;}
[0-9]+ {std::cout << "Number:" << std::string(yytext, yyleng) << "\n"; return 2;}
{WhiteSpace}+ {/*IgnoreSpace*/}
. {std::cout << "Unknown\n"; return 3;}
%%
int yyFlexLexer::yywrap()
{
return true;
}
像这样构建:
flex --header-file=Lexer.h -t Lexer.l > Lexer.cpp
注意:我使用上面这行是因为我讨厌生成的文件名,这样我就可以使用我喜欢的文件名。
现在您可以使用标准 C++ 流(如 std::cin 和 std::ifstream)。
#include "Lexer.h"
int main()
{
yyFlexLexer lex(&std::cin); // Pass a pointer to any input stream.
while (lex.yylex())
{
}
std::ifstream file("text");
yyFlexLexer anotherLexer(&file);
while(anotherLexer.yylex())
{
}
}
关于c++ - Flex/Lex 从输入文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32342333/