In CS50 we now have to make multiple functions (I guess they want us to get used to objective-oriented programming for the python part later) and return the value to the main function. When I execute the code enter a text I keep getting:
0 letters, 0 words, 0 sentences, Before Grade 1
To debug I added print("&i", clindex); --> this printed "-2147483648" and no matter how I change the input text, this is the same.
When I use the same code in the main function, it works.
Here is the code:
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
// Add functions.
int count_letters(string txt);
int count_words(string txt);
int count_sentences(string txt);
// Declare global variables.
float l;
float w;
float s;
int main(void)
{
// Ask user for string, store in txt.
string txt = get_string("Enter your text: ");
int i = strlen(txt);
// Convert letters and sentences to avg / 100 w.
float L = 100 * (l / w);
float S = 100 * (s / w);
// Calc coleman-liau index
int clindex = round(0.0588 * L - 0.296 * S - 15.8);
printf("%i\n", clindex);
// Print letter count
printf("%d letters\n", (int)l);
// Print word count
printf("%d words\n", (int)w);
// Print sentence count
printf("%d sentences\n", (int)s);
// Printf below grade 1 (clindex < 1), "Grade clindex" if clindex < 16, printf "Grade 16+".
if (clindex < 1)
{
printf("Before Grade 1\n");
}
else if (clindex > 16)
{
printf("Grade 16+\n");
}
else
{
printf("Grade %i\n", clindex);
}
}
int count_letters(string txt)
{
// Count letters
l = 0;
for (int i = 0, n = strlen(txt); i < n; i++)
{
// If the txt is between a-z (97 - 122) or A-Z (65 - 90), increase letter count.
if ((txt[i] >= 'a' && txt[i] <= 'z') || (txt[i] >= 'A' && txt[i] <= 'Z'))
{
l++;
}
}
return l;
}
int count_words(string txt)
{
// Count words
w = 1;
for (int i = 0, n = strlen(txt); i < n; i++)
{
// If there is a space (ascii 32), then increase word count.
if (txt[i] == ' ')
{
w++;
}
}
return w;
}
int count_sentences(string txt)
{
s = 0;
for (int i = 0, n = strlen(txt); i < n; i++)
{
if (txt[i] == '.' || txt[i] == '!' || txt[i] == '?')
{
s++;
}
}
return s;
}