c++ - Flex/Lex 从输入文件读取

标签 c++ file flex-lexer

我有一个 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/

相关文章:

c - 如何使用 Flex/Bison 创建真正的编译器?

php - 从 PHP 连接到 C++ 服务器太多次导致访问冲突异常

c++ - 为什么字符串使用 char*?

C++ : how can I fourier transform an array into an other array of different size using fftw3

java - 用java限制文件写入?

c++ - 将数据实时写入文件或在程序关闭时写入文件更好吗?

c++ - 删除 QNetworkReply 的最佳方法是什么?

c++ - 从 .h 和 .cpp 文件定义纯虚函数会产生链接器错误?

parsing - 如何使用 Flex 实现两遍扫描仪?

error-handling - 如何在Bison中防止默认 “syntax error”