107 lines
2.2 KiB
C
107 lines
2.2 KiB
C
#include <cs50.h>
|
|
#include <ctype.h>
|
|
#include <math.h>
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
|
|
int count_letters(string text);
|
|
int count_words(string text);
|
|
int count_sentences(string text);
|
|
|
|
int main(void)
|
|
{
|
|
// Prompt the user for some text
|
|
string text = get_string("Text: ");
|
|
|
|
int words = 1;
|
|
int sentences = 0;
|
|
int letters = 0;
|
|
|
|
// Count the number of letters, words, and sentences in the text
|
|
for (int i = 0, n = strlen(text); i < n; i++)
|
|
{
|
|
if (text[i] == ' ')
|
|
{
|
|
words += 1;
|
|
}
|
|
else if (text[i] == '.' || text[i] == '!' || text[i] == '?')
|
|
{
|
|
sentences += 1;
|
|
}
|
|
else
|
|
{
|
|
if (isalpha(text[i]))
|
|
{
|
|
letters += 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
// printf("Letters: %i\n", letters);
|
|
// printf("Words: %i\n", words);
|
|
// printf("Sentences: %i\n", sentences);
|
|
|
|
// Compute the Coleman-Liau index
|
|
float L = (float) letters / (float) words * 100;
|
|
float S = (float) sentences / (float) words * 100;
|
|
float X = 0.0588 * L - 0.296 * S - 15.8;
|
|
int Xint = (int) round(X);
|
|
// printf("L=%f, S=%f, X=%f, Xint=%i", L, S, X, Xint);
|
|
|
|
// Print the grade level
|
|
if (Xint >= 16)
|
|
{
|
|
printf("Grade 16+\n");
|
|
}
|
|
else if (Xint < 1)
|
|
{
|
|
printf("Before Grade 1\n");
|
|
}
|
|
else
|
|
{
|
|
printf("Grade %i\n", Xint);
|
|
}
|
|
}
|
|
|
|
int count_letters(string text)
|
|
{
|
|
// Return the number of letters in text
|
|
int letters = 0;
|
|
for (int i = 0, n = strlen(text); i < n; i++)
|
|
{
|
|
if (isalpha(text[i]))
|
|
{
|
|
letters += 1;
|
|
}
|
|
}
|
|
return letters;
|
|
}
|
|
|
|
int count_words(string text)
|
|
{
|
|
// Return the number of words in text
|
|
int words = 0;
|
|
for (int i = 0, n = strlen(text); i < n; i++)
|
|
{
|
|
if (text[i] == ' ' && (text[i - 1] != '.' || text[i - 1] != '!' || text[i - 1] != '?'))
|
|
{
|
|
words += 1;
|
|
}
|
|
}
|
|
return words;
|
|
}
|
|
|
|
int count_sentences(string text)
|
|
{
|
|
// Return the number of sentences in text
|
|
int sentences = 0;
|
|
for (int i = 0, n = strlen(text); i < n; i++)
|
|
{
|
|
if (text[i] == '.' || text[i] == '!' || text[i] == '?')
|
|
{
|
|
sentences += 1;
|
|
}
|
|
}
|
|
return sentences;
|
|
}
|