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.
#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;
}
Comments
Leave a comment