Search code examples
ccs50readability

CS50 problem 2 - Readability // The grading is not working properly


Hi there I am having an issue with CS50 problem set 2 specifically the readability task. The issue is when I input the preset values that are on the website to try out to test your program some of them don't work I am not sure why it doesn't work can anyone help me

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

int main(void){
  string text = get_string("Text: ");
  int letter_count = 0;
  int word_count = 0;
  int sentence_count = 0;

  for( int i=0;i < strlen(text);i++){

    if (isalpha(text[i])){
        letter_count ++;
    }
    else if(text[i] == ' '){
        word_count ++;
    }
    else if(text[i] == '.' || text[i] == '!' || text[i] == '?')
    {
        sentence_count ++;
    }
  }
  float L = ((float)letter_count / (float)word_count) * 100;
  float S = ((float)sentence_count / (float)word_count) * 100;
  float index = 0.0588 * L - 0.296 * S - 15.8;

  if (index <= 16 && index >= 0)
  {
    printf("Grade %i\n", (int) round(index));
  }
  else if (index >= 16)
  {
    printf("Grade 16+\n");
  }
  else{
    printf("Before Grade 1\n");
  }
  printf("%i Letter(s)\n", letter_count);
  printf("%i Word(s)\n", word_count+1);
  printf("%i Sentence(s)\n", sentence_count);
}

Solution

  • When you check spaces for counting words, one space means ' ' indeed a word coming after. But if there is a space, it means there must be always a word in front. Like below;

    Hello World.

    Here there are two words, but one space. To fix this, initializing word variable with 1 should do the work.

    int word_count = 1;