Answer to Question #207215 in C for Ali khan

Question #207215

Write a program to carry out the following:

 To read a text file “TRIAL.TXT” consisting of a maximum of 50 lines of text, 

each line with a maximum of 80 characters.

 Count and display the number of words contained in the file.

 Display the total number of four letter words in the text file.

Assume that the end of a word may be a space, comma or a full-stop followed by one 

or more spaces or a newline character.


1
Expert's answer
2021-06-17T05:00:21-0400


#include <stdio.h>
#include <ctype.h>


int word_count(char* line)
{
    int count = 0;
    char *p = line;
    int in_word = 0;


    while (*p) {
        if (isalpha(*p)) {
            if (! in_word) {
                in_word = 1;
                count++;
            }
        }
        else if (in_word && (*p == '.' || *p == ',')) {
            if (*(++p) && isspace(*p)) {
                in_word = 0;
            }
        } else if (in_word && isspace(*p)) {
            in_word = 0;
        }
        p++;
    }
    return count;
}


int word4_count(char* line)
{
    int count = 0;
    char *p = line;
    int in_word = 0;


    while (*p) {
        if (isalpha(*p)) {
                in_word++;
        }
        else if (in_word && (*p == '.' || *p == ',')) {
            if (*(++p) && isspace(*p)) {
                if (in_word == 4) {
                    count++;
                }
                in_word = 0;
            }
        } else if (in_word && isspace(*p)) {
            if (in_word == 4) {
                count++;
            }
            in_word = 0;
        }
        else if (in_word) {
            in_word++;
        }
        p++;
    }
    return count;
}


int main()
{
    char buf[81];
    FILE* f;
    int count=0, count4=0;

    f = fopen("TRIAL.TXT", "r");
    while (fgets(buf, 81, f)) {
        count += word_count(buf);
        count4 += word4_count(buf);
    }
    fclose(f);
    printf("There are total %d words and %d 4-letters words\n", count, count4);

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS