title: Lex program to count number of lines, characters, digits, and key words
body: <p>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:</p>
  
  <pre><code>%{
  #include &lt;stdio.h&gt;
  
  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++;}
  
  &lt;COMMENT&gt;"*/"[\t]*\n {BEGIN 0; NumberOfComments++;}
  &lt;COMMENT&gt;"*/" {BEGIN 0;}
  &lt;COMMENT&gt;\n {NumberOfComments++;}
  &lt;COMMENT&gt;.\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 &gt; 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; 
  }
  </code></pre>
  
  <p>Whenever I run my input file with the source it give me the wrong output. For instance the output of the file should be:</p>
  
  <p>Output:</p>
  
  <pre><code>Number of Keywords: 3
  
  Number of Characters: 196
  
  Number of Lines: 17
  
  Number of Digits: 3
  </code></pre>
  
  <p>However the output it is currently producing is:</p>
  
  <p>Output:</p>
  
  <pre><code>Number of keywords: 0
  
  Number of Characters: 3
  
  Number of Lines: 7
  
  Number of Digits: 0   
  </code></pre>
  
  <p>I suspect it has to do with my regular expressions, any help would be appreciated as I am still learning regex!</p>
  
  <p>Here is my input file contents:</p>
  
  <pre><code>/*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
  </code></pre>