Why does my code repeat the output of the grade level when ran. This is Harvard's CS50 pset2 called readability

Viewed 37

I thought the code was fine until I tested using "Red fish, blue fish, one fish, two fish." and it gave me the correct output (Below Grade 1) but it said it a bunch of times. I know the problem is most likely in my loop but I can't find the issue in it.

int main(void)
    {
        //Text from User
        string text = get_string("Text: ");
    
        int letters = 0;
        int words = 1;
        int sentences = 0;
    
        for (int i = 0; i < strlen(text); i++)
        {
            if (isalpha(text[i]))
            {
                letters++;
            }
    
            else if (text[i] == ' ')
            {
                words++;
            }
    
            else if (text[i] == '.' || text[i] == '!' || text[i] == '?')
            {
                sentences++;
            }
    
            float L = (float) letters / (float) words * 100;
            float S = (float) sentences / (float) 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);
            }
1 Answers

You are missing header files, depend on code you didn't share with us (get_string()) and your source is truncated. You need to do the calculations after the loop:

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

typedef char * string;
#define LEN 1000

string get_string(const char *prompt) {
    printf("%s", prompt);
    string s = malloc(LEN + 1);
    if(!fgets(s, LEN, stdin)) {
        free(s);
        return NULL;
    }
    size_t n = strlen(s);
    if(n) n--; // strip trailing newline
    s[n] = '\0';
    return s;
}

int main(void) {
    string text = get_string("Text: ");
    int letters = 0;
    int words = 1;
    int sentences = 0;
    for (size_t i = 0; i < strlen(text); i++) {
        if (isalpha(text[i])) {
            letters++;
        } else if (text[i] == ' ') {
            words++;
        } else if (text[i] == '.' || text[i] == '!' || text[i] == '?') {
            sentences++;
        }
    }
    float L = (float) letters / (float) words * 100;
    float S = (float) sentences / (float) 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);
    }
    free(text);
    return 0;
}
Related