Search code examples
clexflex2

There is a problem in my lex code, output is not generated by reading an input file


Question is to write a lex Program to Scan and Count the number of characters, words, digits, vowels,consonant, special characters and lines in a file.

I have written the code. I also have tried asking chat-gpt for any possible errors or problems, but still I could not get the write answer.

Here is the code.

%{
#include<stdio.h>
int lines = 0;
int vowels = 0;
int consonants = 0;
int characters = 0;
int digits = 0;
int words = 0;
int special_char = 0;
%}

%%
[a-zA-Z] {
    characters++;
    if (strchr("aeiouAEIOU", yytext[0]))
        vowels++;
    else
        consonants++;
}

[0-9] {
    characters++;
    digits++;
}

[ \t\n] {
    characters++;
    if (yytext[0] == '\n')
        lines++;
}

. {
    characters++;
    special_char++;
}

%%

int yywrap(){ return 1; }
int main(int argc, char* argv[]) {

    FILE* input_file = fopen("input.txt", "r");
    if (!input_file) {
        printf("Error opening the file.\n");
        return 1;
    }
    
    char buffer[100];
    printf("Input text from the file:\n");
    while (fgets(buffer, sizeof(buffer), input_file) != NULL) {
        printf("%s", buffer);
    }
    printf("\n");
    
    yyin = input_file;
    yylex();

    printf("Character count: %d\n", characters);
    printf("Word count: %d\n", words); // Add this line to print the word count.
    printf("Digit count: %d\n", digits);
    printf("Vowel count: %d\n", vowels);
    printf("Consonant count: %d\n", consonants);
    printf("Special character count: %d\n", special_char);
    printf("Line count: %d\n", lines);

    fclose(input_file);
    return 0;
}

cmd:

flex prac.l

gcc -C lex.yy.c

./a.out

output is like this.

Input text from the file:
My name is xyz.
123123 @!$%(@#)
124adasd31231

Character count: 0
Word count: 0
Digit count: 0
Vowel count: 0
Consonant count: 0
Special character count: 0
Line count: 0

where could be the error? please help.


Solution

  • The fgets loop is consuming the contents of the file such that feof(input_file) will be true after the loop (assuming no error occurs). This leaves nothing for yylex to process.

    rewind the file after reading it.

    rewind(input_file);
    yyin = input_file;
    yylex();
    

    Results:

    Input text from the file:
    My name is xyz.
    123123 @!$%(@#)
    124adasd31231
    
    Character count: 46
    Word count: 0
    Digit count: 14
    Vowel count: 5
    Consonant count: 11
    Special character count: 9
    Line count: 3