0
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>


int main(void)
{
    //Retrieve string of text from user
    string s = get_string("Text: ");
    printf("Letters: ");

    //Initialize counter for letters
    int letters = 0;

    //Find number of letters in sentence
    for(int i = 0, n = strlen(s); i < n; i++)
    {
        if(isalpha(s[i]) != 0)
        {
            letters++;
        }
    }
    printf("%i", letters);
    printf("\n");
    printf("Words: ");

    //Initialize counter for words
    int words = 0;
    int spaces= 0;

    //Find number of words in a sentence
    for(int j = 0, n = strlen(s); j < n; j++)
    {
        if(isblank(s[j]) != 0)
        {
            spaces++;
            words = spaces + 1;
        }
    }
    printf("%i", words);
    printf("\n");
    printf("Sentences: ");

    //Initialize counter for sentences
    int sentences = 0;
    char punctuation[] = {'!','.','?'};

    //Check string for punctuation from array
    //Increment sentence count if found
    if ispunct(punctuation[1])
    {
        sentences++;
    }
    else
    {
        sentences = sentences + 0;
    }
    if ispunct(punctuation[2])
    {
        sentences++;
    }
    else
    {
        sentences = sentences + 0;
    }
    if ispunct(punctuation[3])
    {
        sentences++;
    }
    else
    {
        sentences = sentences + 0;
    }
    if ispunct(punctuation[4])
    {
        sentences++;
    }
    else
    {
        sentences = sentences + 0;
    }
    printf("%i", sentences);
    printf("\n");
}

1 Answer 1

0

Program needs some refinement. But let's talk about sentences tests first.

The code is comparing against punctuation[3] and punctuation[4]. These don't exist. There are only 3 elements, numbered 0,1 and 2. So, this code is only going to recognize questions as sentences.

The code runs through the text using 3 for loops, one for letters, one for words and one for sentences. Why do 3 passes through the text when you can do it in one? Just check each letter for what it is and increment the appropriate vars as you go.

Think about program efficiency on a large scale. What if this code had to examine Tolstoy's "War and Peace", or the entire contents of a publisher's inventory to calculate readability? Or the Library of Congress? The execution time could be cut to 1/3 by doing one pass instead of 3.

Happy programming!

If this answers your question, please click on the check mark to accept. Let's keep up on fourm maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .