私はLexを初めて使用します。この問題の完全な要件は、次のとおりです。
テキストファイル内の文字、単語、および行をカウントし、カウントを報告するプログラムを生成するLex入力ファイルを記述します。句読点やスペースを含まない、文字や数字の任意のシーケンスになるように単語を定義します。句読点と空白は単語としてカウントされません。
今、私はコードを書き留めました:
%{
#include <stdio.h>
#include <stdlib.h>
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;
}
私はそれをテキストファイルでテストしました:
this is line #1
line #2 is here
!@#$%^&*()
haha hey hey
そして、私は出力を得ました
#1
#2
!@#$%^&*()
Number of characters: 30; Number of words: 45; Number of lines: 4
しかし、正しい出力は
Number of characters: 30; Number of words: 11; Number of lines: 4
「単語数」のエラーは、文字数ごとにどういうわけか原因だと思いますが、これに対処するためにプログラムをどのように変更すればよいでしょうか。
また、不要な出力(句読点)が出てきます。それらを回避するためにプログラムをどのように変更する必要がありますか?
どうもありがとうございます。