0

My Readability code keeps on creating the outputs of the wrong grade when I try to execute it. When inputting the text, 'When he was nearly thirteen, my brother Jem got his arm badly broken at the elbow. When it healed, and Jem's fears of never being able to play football were assuaged, he was seldom self-conscious about his injury. His left arm was somewhat shorter than his right; when he stood or walked, the back of his hand was at right angles to his body, his thumb parallel to his thigh", it returns as Grade 14. I do not know what I am doing wrong. I have tried to tinker around some lines but nothing seems to be working. Please help!

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

 //index = 0.0588 * L - 0.296 * S - 15.8
 // L = Number of letters / 100 words; S = number of sentences / 100 words

int main(void)
{
    string text = get_string("Text: ");
    // l = letters , s = sentences , w = words
    int l = 0;
    int s = 0;
    int w = 1;

    for (int i = 0; i < strlen(text); i++)
    {
        if (text[i] != '\0')
        {
            l++;
        }
        if (text[i]== '.' || text[i] == '!' || text[i] == '?')
        {
            s++;
        }
        if (text[i] == ' ')
        {
            w++;
        }
    }
    float la = 100.00 * ((float)l / w);
    float sa = 100.00 * ((float)s / w);
    
    float ind = (0.0588 * la) - (0.296 * sa) - 15.8;
    int index = round(ind);
    
    if(ind > 16)
    {
        printf("Grade 16+\n");
    }
    else if(ind < 1)
    {
        printf("Before Grade 1\n");
    }
    else{
        printf("Grade %i\n", index);
    }
    printf("Number of Letters: %i\n", l);
    printf("Number of Sentences: %i\n", s);
    printf("Average letters per 100 words: %f\n", la);
}

2 Answers 2

0

Looks like l is trending high. It counts every character in the text except the terminating null byte (which never makes it into the loop anyway!). Check out man isalpha to get back on track. This may not be the only problem in the code.

0

Here's a major problem.

    if (text[i] != '\0')
    {
        l++;
    }

This is counting EVERYTHING, not just letters.

Hint: isalpha() is your friend.

2
  • I changed if (text[i] != '\0') to become if (isalpha(text) != 0) s++; , but when I did that, the program executed with a Segmentation Fault. I am very new to any type of CS so I do not know how to fix it. I added the library where isalpha comes from, so I am very confused.
    – stanloona
    Commented Aug 30, 2020 at 3:52
  • That's because "text" is a string, not a char. You need to give it a single char as input, Try this:if(isalpha(text[i]))
    – Cliff B
    Commented Aug 30, 2020 at 3:58

You must log in to answer this question.

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