title: Lex: a small program to count words in the input
body: <p>I'm extremely new to Lex and the complete requirement of this problem is as follows:</p>
  
  <blockquote>
    <p>Write a Lex input file that will produce a program that counts
    characters, words, and lines in a text file and reports the counts.
    Define a word to be any sequence of letters and/or digits, without
    punctuation or spaces. Punctuation and white space do not count as
    words.</p>
  </blockquote>
  
  <p>Now I've written down the code:</p>
  
  <pre><code>%{
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  int cno = 0, wno = 0, lno = 0; /*counts of characters, words and lines */
  %}
  character [a-z]
  digit [0-9]
  word ({character}|{digit})+[^({character}|{digit})]
  line \n
  %%
  {line} { lno++; REJECT; }
  {word} { wno++; REJECT; }
  {character} { cno++; }
  %%
  void main()
  { yylex();
    fprintf(stderr, "Number of characters: %d; Number of words: %d; Number of lines: %d\n", cno, wno, lno);
    return;
  }
  </code></pre>
  
  <p>I tested it with the text file:</p>
  
  <pre><code>this is line #1
  line #2 is here
  !@#$%^&amp;*()
  haha hey hey
  </code></pre>
  
  <p>And I got the output</p>
  
  <pre><code>   #1
   #2  
  !@#$%^&amp;*()
  
  Number of characters: 30; Number of words: 45; Number of lines: 4
  </code></pre>
  
  <p>But the correct output should be</p>
  
  <pre><code>Number of characters: 30; Number of words: 11; Number of lines: 4
  </code></pre>
  
  <p>I guess the error of "number of words" should be somehow due to every count of characters, so how should I modify my program to tackle with this? </p>
  
  <p>Also, there're some unnecessary output coming out (those punctuations). How should I modify my program to avoid them?</p>
  
  <p>Thank you very much.</p>