I have been working on developing a lex scanner however when I feed it my input file it is producing the wrong output. Here is my source code:
%{
#include <stdio.h>
int NumberOfLines=0;
int NumberOfChar=0;
int NumberOfIntegers=0;
int KWCount=0;
int NumberOfComments=0;
%}
DIGIT [0-9]*
ID [a-z][a-z0-9]*
%x COMMENT
%option noyywrap
%%
^[\t]*"/*" {BEGIN COMMENT;}
^[\t]*"/*".*"*/"[\t]*\n {NumberOfComments++;}
<COMMENT>"*/"[\t]*\n {BEGIN 0; NumberOfComments++;}
<COMMENT>"*/" {BEGIN 0;}
<COMMENT>\n {NumberOfComments++;}
<COMMENT>.\n {NumberOfComments++;}
\n {NumberOfLines++, NumberOfChar++; NumberOfChar +=strlen(yytext);}
. {NumberOfChar++; NumberOfChar +=strlen(yytext);}
{DIGIT} {NumberOfIntegers++; NumberOfChar +=strlen(yytext); }
{DIGIT}+"."{DIGIT}* {
printf("A flot: %s (%g) \n", yytext, atof(yytext));
NumberOfChar +=strlen(yytext);
}
if|else|while|return {
printf("A keyword: %s\n", yytext); KWCount++;
NumberOfChar +=strlen(yytext);
}
{ID} {
printf("An identifier: %s\n", yytext);
NumberOfChar +=strlen(yytext);
}
"{"[^}\n]*"}" {
/*each up one-line comments*/
NumberOfChar +=strlen(yytext);
}
%%
int main(int argc, char **argv){
++argv, --argc; /*skip over program name */
if (argc > 0)
yyin = fopen(argv[0], "r");
else
yyin = stdin;
yylex();
printf("Character count: %d",NumberOfChar);
printf("\n");
printf("Number count: %d",NumberOfIntegers);
printf("\n");
printf("Keyword count: %d",KWCount);
printf("\n");
printf("Line count: %d",NumberOfLines);
printf("\n");
printf("Comment count: %d", NumberOfComments);
printf("\n");
return 0;
}
Whenever I run my input file with the source it give me the wrong output. For instance the output of the file should be:
Output:
Number of Keywords: 3
Number of Characters: 196
Number of Lines: 17
Number of Digits: 3
However the output it is currently producing is:
Output:
Number of keywords: 0
Number of Characters: 3
Number of Lines: 7
Number of Digits: 0
I suspect it has to do with my regular expressions, any help would be appreciated as I am still learning regex!
Here is my input file contents:
/*comment 1*/
/*comment
comment 2
*/
/*comment 3*
*/if this is a line
{comment 4}
int i = 789;
int j = 689;
if i == 172 then
{comment 5}
else
{comment 6}
{comment 7}
/*8 comments
*
*/
end