0

whenever I try to run my readability code I always get that I have no words or sentences. Additionally, whenever I run my code the number of letters seems to include spaces eventhough I am using the isaplha function. For example, when I type in "hello world" I get "Letters: 11, Words: 0, Sentences: 0". Does anybody know what's wrong with my code? Thanks.

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

int main(void)
{
    string text = get_string("Text: ");
    int letters, words, sentences, i; 
    letters = 0;
    words = 0;
    sentences = 0;
    i = 0;
    int x = isalpha(text[i]);
    int y = isspace(text[i]);
    int z = text[i] == '.' || text[i] == '!' || text[i] == '?';
    int length = strlen(text);
    for (i = 0; i < length; i++)
    {
        if (x)
            letters++;
        if (y)
            words++; 
        if (z)
            sentences++;
    }
    printf ("Letters: %i\n", letters);
    printf ("Words: %i\n", words);
    printf ("Sentences: %i\n", sentences);
}
0

The logic of this code is bad. It sets x, y and z based on the first character in the string, all before the start of the for loop. Since it isn't looking at text[] inside the for loop, it isn't looking at the subsequent chars. It's just looping through the length count and incrementing x.

This code can be both fixed and simplified. It needs to look at each char of text[] inside the for loop, not before. Also, the code should test for an alpha and increment a counter if true. Same idea checking for words and for sentences.

A major rewrite is in order.

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

You must log in to answer this question.

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