Flex / Lex从输入文件中读取

时间:2015-09-01 23:19:15

标签: 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;
}

4 个答案:

答案 0 :(得分:0)

我自己并不熟悉词法分析器,但这似乎描述了你想要做的事情以及更多:http://epaperpress.com/lexandyacc/download/LexAndYaccTutorial.pdf

答案 1 :(得分:0)

@KompjoeFriek,感谢您的链接:)

@ error_404,此代码适用于我

%{
    #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(int ac, char **av)
{
    FILE    *fd;

    if (ac == 2)
    {
        if (!(fd = fopen(av[1], "r")))
        {
            perror("Error: ");
            return (-1);
        }
        yyset_in(fd);
        yylex();
        fclose(fd);
    }
    else
        printf("Usage: a.out filename\n");
    return (0);
}

答案 2 :(得分:0)

我喜欢flex的C ++输出。

Lexer.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())
    {
    }
}

答案 3 :(得分:0)

您必须将变量 df <- data.frame(x = 1:5, y = c("cloch/51.wav", "grand/Grand_bombarde/02-suchy_Grand_bombarde/038-D.wav", "grand/Grand_bombarde/02-suchy_Grand_bombarde/039-D#.wav", "AB_AeolinaL/025-C#.wav", "AB_AeolinaL/026-D.wav")) # I define a function that separates a string at each "/" # throws the last piece and reattaches the pieces cut_str <- function(s) { st <- head((unlist(strsplit(s, "\\/"))), -1) r <- paste(st, collapse = "/") return(r) } # through the sapply function I get the desired result new_strings <- as.vector(sapply(df$y, FUN = cut_str)) new_strings [1] "cloch" [2] "grand/Grand_bombarde/02-suchy_Grand_bombarde" [3] "grand/Grand_bombarde/02-suchy_Grand_bombarde" [4] "AB_AeolinaL" [5] "AB_AeolinaL" 设置为要读取的文件的文件处理程序。

我最喜欢的 Flex 和 Bison 教程是来自 aquamentus 的 this one

来自同一个教程,这里有一个关于如何使用 Flex 读取文件的片段。

yyin