0

I have been having some trouble forming a proper global function for CS50 pset2 readability. The code has no error after compiling but the index will not count. I'm not sure if the global counter variables count_letters, count_words and count_sentences are working well.

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

int count_letters(string text);
int count_words(string text);
int count_sentences(string text);
    
int main(void)
{
    string s = get_string("Text: ");
    
    int letters = count_letters(s);
    int words = count_words(s);
    int sentences = count_sentences(s);
    float L = ((float) letters / words) * 100; 
    float S = ((float) sentences / words) * 100; 
    
    int index = round(0.0588*L - 0.296*S - 15.8);
    
    if (index < 1)
        printf("Before Grade 1\n");
    else if (index > 16)
        printf("Grade 16+\n");
    else
        printf("Grade %i\n", index);
}

int count_letters(string text)
{
    int count = 0;
    for (int i = 0, len = strlen(text); i < len; i++)
    {
        if (isalpha(text[i]))
        return count++;
    }
    return 0;
}

int count_words(string text)
{
    int count = 0;
    for (int i = 0, len = strlen(text); i < len; i++)
    {
        if ((i == 0 && text[i] != ' ')||(text[i] != len-1 && text[i]== ' ' && text[i+1] != ' '))
        return count++;
    }
    return 0;
}
    
int count_sentences(string text)
{
    int count = 0;
    for (int i = 0, len = strlen(text); i < len; i++)
    {
        if (text[i] == '.' || text[i] == '?' || text[i] == '!' )
        return count++;
    }
    return 0;
}
0

One way to know if the functions are working well is to "see" what they are returning. That can be accomplished using debug50 or adding printfs so you can see what the computer sees.

letters is always 1. When the first "alpha" is encountered, functions returns to main.

words is (probably) always 0. Assuming the first character (text[0]) is not a space. Same problem as with letters, it returns to main.

sentences is always 1. When it detects the first sentence delimiter, it returns to main.

You must log in to answer this question.

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