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;
}