counting the number of sentences in a paragraph in c

10,826

Solution 1

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");

Solution 2

Here you have the solution to your problem:

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

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

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

    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();
}

The problem with your code is that the innermost while loop was consuming all the characters. Whenever you enter there and you type a dot or a newline it stays inside that loop because ch is different from a blank. However, when you exit from the innermost loop you risk to remain stuck at the second loop because ch will be a blank and so always different from '.' and '\n'. Since in my solution you only acquire a character in the innermost loop, in the other loops you need to "eat" the blank and the dot in order to go on with the other characters.

Checking these conditions in the two inner loops makes the code work. Notice that I removed some of your prints.

Hope it helps.

Edit: I added the instructions to print what you type and a last check in the while loop after sentences++ to check the blank, otherwise it will count one word more.

Solution 3

I think the problem is because of your outer while loop's condition. It checks for a newline character '\n', as soon as it finds one the loop terminates. You can try to include your code in a while loop with the following condition

while((c=getchar())!=EOF)

this will stop taking input when the user presses Ctrl+z

Hope this helps..

Solution 4

You can implement with ease an if statement using while statement:

bool flag = true;
while(IF_COND && flag)
{
    //DO SOMETHING
    flag = false;
}

just plug it in a simple solution that uses if statements.

For example:

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

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

    bool if_flag;

    while ((ch = getch()) != '\n')
    {
        count++;
        if_flag = true;
        while (ch==' ' && if_flag)
        {
            words++;
            if_flag = false;
        }
        if_flag = true;
        while (ch=='.' && if_flag)
        {
            sentences++;
            if_flag = false;
        }
    }

    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();
}

Solution 5

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

int main(void){

int sentence=0,characters =0,words =0,c=0,inside_word = 0,temp =0;
// while ((c = getchar()) != EOF) 
while ((c = getchar()) != '\n') {
   //a word is complete when we arrive at a space after we 
  // are inside a word or when we reach a  full stop

    while(c == '.'){
        sentence++;
        temp = c;
        c = 0;
    }
     while (isalnum(c)) {
        inside_word = 1;
        characters++;
        c =0;
    }
    while ((isspace(c) || temp == '.') && inside_word == 1){
        words++;
        inside_word = 0;
        temp = 0;
        c =0;
    }
}
printf(" %d   %d   %d",characters,words,sentence);
return 0;
}

this should do it,

isalnum checks if the letter is alphanumeric, if its an alphabetical letter or a number, I dont expect random ascii characters in my sentences in this program.

isspace as the name says check for space

you need the ctype.h header for this. or you could add in

   while(c == ' ') and whie((c>='a' && c<='z') || (c >= 'A' && c<='Z') 

if you don't want to use isalpace and isalnum, your choice, but it will be less elegant :)

Share:
10,826
dnclem
Author by

dnclem

Updated on June 15, 2022

Comments

  • dnclem
    dnclem almost 2 years

    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?

  • Admin
    Admin about 10 years
    It would be a lot easier if he was allowed to use if/else and switch but he said: only using printf, getch() and a while loop
  • wildplasser
    wildplasser about 10 years
    char ch; should be int ch; And you should add a case for EOF to the switch.
  • kuroi neko
    kuroi neko about 10 years
    @wildplasser OK for the int, as for EOF, bah, this is just for TurboC so EOF is unlikely to show up. The point was to illustrate how a parser generally works without wandering into minute details.
  • dnclem
    dnclem about 10 years
    Well even then I would have to use an if and switch statement, no? Which I can't.
  • wildplasser
    wildplasser about 10 years
    It is not that hard to rewite the switch(){} into a couple of if(){}s. BTW : while (ch != '/n'); should be while (ch != '\n');
  • Admin
    Admin about 10 years
    The whole problem is about not using ifs
  • dnclem
    dnclem about 10 years
    I think those prints were need since now it doesn't print any space. Also, it still doesn't "end" the code when I hit enter.
  • kuroi neko
    kuroi neko about 10 years
    @wildplasser yep, another typo bites the dust. Thanks. Anyway, I feel like I'm wasting my time here. Either the OP musunderstood the conditions or the exercise is plain wrong, IMHO.
  • BLUEPIXY
    BLUEPIXY about 10 years
    and '.' doesn't print. and no count.
  • dnclem
    dnclem about 10 years
    I didn't. I know my teacher is asking a really dumb thing. I'm sorry if I'm wasting other people's time (and this is bugging me too - I've spent 3 hours on this dumb thing so far). It doesn't help that I'm using a really awful compiler too.
  • dnclem
    dnclem about 10 years
    You are using a bool though. As silly as it sounds, my teacher doesn't want this.
  • kuroi neko
    kuroi neko about 10 years
    In that case I can only sympathize. There are enough horrible programmers around, we don't need teachers to teach stupid ways of doing things :). When I was a project manager, had one of my team members produced a similar piece of code, I would have given him hell and asked ihm to rewrite it right away.
  • zvisofer
    zvisofer about 10 years
    It does sound this way. change it to an int. You are using ints, are you not?
  • dnclem
    dnclem about 10 years
    Agreed. It's such a shame when you have an amazing programming teacher one semester, and then the next one you have one with horrible teaching methods. Instead of praising students for using functions which haven't even been taught he cancels the entire thing.
  • mike
    mike about 10 years
    For me it prints the results and at the end waits for a character before terminating the program, because of the final getch().
  • dnclem
    dnclem about 10 years
    Are you sure? I tested your code in CodeBlocks and TurboC both, and none show spaces or print the output.
  • mike
    mike about 10 years
    By the way you can overcome the problem of printing what you write (i.e. do the echo) by putting a printf after each getch() (remember the parenthesis in the while loops of a single line) and you remove the one before count++.
  • dnclem
    dnclem about 10 years
    Thank you. After hours of testing different things, yours is the only code that actually works. Is it possible to break the loop without using the break command though? Or would that mean changing the entire code?
  • BLUEPIXY
    BLUEPIXY about 10 years
    @david It can replace the break the method of zvisofer.
  • tesseract
    tesseract about 10 years
    @BLUEPIXY thanks for that, fixed everything, there were a few mistakes, compiled and tested.