I am trying to code a program that count the number of letters, words, and sentences in a text. I may assume that a letter is any lowercase character from a to z or any uppercase character from A to Z, any sequence of characters separated by spaces should count as a word, and that any occurrence of a period, exclamation point, or question mark indicates the end of a sentence.
So far, I could count both the number of letters and sentences correctly, but I miss out on the number of words:
e.g. yes!
The output should be: 3 letter(s) 1 word(s) 1 sentence(s)
What I get is: 3 letter(s) 0 word(s) 1 sentence(s)
UPDATE: It works fine now after typing out another (words++) in the end right before the printf function. Thanks for the help guys :).
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
string text = get_string("Enter text: ");
printf("Output:\n");
int lettercount;
int words = 0;
int sentences = 0;
int letters = 0;
int length = strlen(text);
for(lettercount = 0; lettercount < length; lettercount++)
{
if(isalpha(text[lettercount]))
{
letters++;
}
else if(text[lettercount] == ' ' || text[lettercount] == '\t' || text[lettercount] == '\n' || text[lettercount] == '\0')
{
words++;
}
else if(text[lettercount] == '.' || text[lettercount] == '!' || text[lettercount] == '?')
{
sentences++;
}
}
words++;
printf("%i letter(s)\n", letters);
printf("%i word(s)\n", words);
printf("%i sentence(s)\n", sentences);
}
text[lettercount] == '\0'
is always false. Also hint:strlen
is O(n) in the length of the string, don't call it each time through your loop. – ThomasYes!
– kaylum