📌  相关文章
📜  Lex程序从文件中获取输入并删除多个空格,行和制表符

📅  最后修改于: 2021-05-25 19:40:12             🧑  作者: Mango

FLEX(快速词法分析器生成器)是一种工具/计算机程序,用于生成Vern Paxson于1987年左右在C中编写的词法分析器(扫描器或词法分析器)。Lex读取指定词法分析器的输入流,并输出在C语言中实现词法分析器的源代码编程语言。函数yylex()是运行Rule Section的主要flex函数。

先决条件: FLEX(快速词法分析器生成器)

例子:

Input:
hello      how
    are       
you?

Output:
hellohowareyou?

Input:
Welcome      to
Geeks    for
      Geeks

Output:
WelcometoGeeksforGeeks

方法:
在读取模式下打开输入文件,并且每当解析器遇到换行符(\ n),空格()或制表符(\ t)时,都将其删除并在输出文件中写入所有其他字符。

输入文件: Input.txt (此程序中使用的输入文件)

下面是实现程序:

/*Lex program to take input from file and 
remove multiple spaces, newline and tab
and write output in a separate file*/
  
% {
    /*Definition section */
    %
}
  
/* Rule: whenever space, tab or 
newline is encounterd, remove it*/
% %
[ \n\t]+ {fprintf(yyout, "");}
.       { fprintf(yyout, "%s", yytext); }
% %
  
int yywrap(){}
  
// driver code 
int main()
{
  
    /* yyin and yyout as pointer
    of File type */
    extern FILE *yyin, *yyout;
  
    /* yyin points to the file input.txt
    and opens it in read mode*/
    yyin = fopen("Input.txt", "r");
  
    /* yyout points to the file output.txt
    and opens it in write mode*/
    yyout = fopen("Output.txt", "w");
  
    yylex();
    return 0;
}

输出:

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。