Search code examples
cwhile-loopcharwordstext-segmentation

counting the number of sentences in a paragraph in c


As part of my course, I have to learn C using Turbo C (unfortunately).

Our teacher asked us to make a piece of code that counts the number of characters, words and sentences in a paragraph (only using printf, getch() and a while loop.. he doesn't want us to use any other commands yet). Here is the code I wrote:

#include <stdio.h>
#include <conio.h>

void main(void)  
{  
clrscr();  
int count = 0;  
int words = 0;  
int sentences = 0;  
char ch;

while ((ch = getch()) != '\n')
{
    printf("%c", ch);
    while ((ch = getch()) != '.')
    {
        printf("%c", ch);
        while ((ch = getch()) != ' ')
        {
            printf("%c", ch);
            count++;
        }
        printf("%c", ch);
        words++;
    }
    sentences++;
}

printf("The number of characters are %d", count);
printf("\nThe number of words are %d", words);
printf("\nThe number of sentences are %d", sentences);
getch();
   }

It does work (counts the number of characters and words at least). However when I compile the code and check it out on the console window I can't get the program to stop running. It is supposed to end as soon as I input the enter key. Why is that?


Solution

  • int ch;
    int flag;
    while ((ch = getch()) != '\r'){
        ++count;
        flag = 1;
        while(flag && (ch == ' ' || ch == '.')){
            ++words;//no good E.g Contiguous space, Space at the beginning of the sentence
            flag = 0;;
        }
        flag = 1;
        while(flag && ch == '.'){
            ++sentences;
            flag=0;
        }
        printf("%c", ch);
    }
    printf("\n");