Saturday 26 June 2021

Counting alphabets and lines in a sentence

This program reads the contents of the file which is given as input. Then counts the number of lines in each sentence and also the alphabets in each sentence. Each English sentence ends with a period(.). 

For example, if the file contains 

This program reads the contents of the file which is given as input. Then counts the number of lines in each sentence and also the alphabets in each sentence. Each English sentence ends with a period. 


Here the first sentence ends in the first line so line count is 1

The second sentence starts in first line and ends in second line, so the line count is 2. 

The third sentence ends in second line, so the line count is 1.


Program

#include <stdio.h>

#include <stdlib.h>

#include <conio.h>


int main()

{

    FILE *f1;

    char fname[20],c,pc;

    int lc=0,ac=0,sc=0,i,flag=0;

    int Line[50],Alpha[50];


    printf("Enter the file name\n");

    gets(fname);

    

    f1 = fopen(fname, "r");

    if (f1==NULL)

    {

printf("File open error");

getch();

exit(0);

    }

    printf("\n\nFile %s contents\n\n",fname);

    while((c=fgetc(f1))!=EOF)

        putchar(c);

    fclose(f1);

    printf("\n\n");

    

    f1=fopen(fname,"r");

    while(!feof(f1))

    {

c=fgetc(f1);

if (c=='\n' && pc !='.')

  ++lc;

if ((c>='a' && c<='z') || (c>='A' && c<='Z'))

  ++ac;

if (c=='.')

{

  ++sc;

  ++lc;

  Line[sc]=lc;

  Alpha[sc]=ac;

  lc=0;

  ac=0;

}

pc=c;

    }

    fclose(f1);

    for(i=1;i<=sc;i++)

    {

          printf("\nThe number of lines and alphabets in sentence %d is %d, %d", i, Line[i],                Alpha[i]);

     } 

   getch();

   return 0;

}


OUTPUT

Enter the file name

test.txt

File test.txt contents


Welcome to the world of programming. It is

fun to learn programming through blogs and

online tutorials.

Happy learning.


The number of lines and alphabets in sentence 1 is 1, 30

The number of lines and alphabets in sentence 2 is 3, 55

The number of lines and alphabets in sentence 3 is 1, 13


No comments:

Post a Comment