📜  Lex程序来识别和计算正数和负数

📅  最后修改于: 2021-06-29 04:06:13             🧑  作者: Mango

给定一些数字,任务是识别正数和负数,并打印负数和正数的计数。

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

例子:

Input : -52
Output : 
negative number=-52
number of positive numbers = 0
number of negative numbers = 1

Input : 63
Output : 
positive number = 63
number of positive numbers = 0
number of negative numbers = 1

下面是实现程序:

/* Lex program to Identify and Count 
Positive and Negative Numbers */ 
%{
int positive_no = 0, negative_no = 0;
%}
   
/* Rules for identifying and counting 
positive and negative numbers*/
%%
^[-][0-9]+ {negative_no++; 
            printf("negative number = %s\n",
                  yytext);}  // negative number
  
[0-9]+ {positive_no++;
        printf("positive number = %s\n", 
                 yytext);} // positive number     
%% 
  
/*** use code section ***/
  
int yywrap(){}
int main()                                              
{
   
yylex(); 
printf ("number of positive numbers = %d,"
        "number of negative numbers = %d\n",
                positive_no, negative_no);
  
return 0; 
}

输出: