Here are the instructions of an exercise that I have to solve for cs50 pset2 readability(copy pasted from the site):
- Your program should count the number of letters, words, and sentences in the text. You 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.
These are not the complete instructions, just the part I have trouble with.
I figured out how to count the number of letters in the text, but I can't figure out how to count the words and sentences. I've tried googling it and using other external resources, but all that pops up is the answer to the problem, which, frankly, feels like cheating. This is my code:
#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<stdbool.h>
#include<ctype.h>
int main (void)
{
int letters = 0;
string text = get_string("Text: ");
int words = 0;
for (int i = 0; i < strlen(text);i++)
{
if(isalpha(text[i]) != 0)
{
letters++;
}
}
printf("Letters: %i\n", letters);
for (int i = 0; i < strlen(text);i++)
{
if (isspace(text[i]) != 0)
{
if(isalpha (text[i] + 1) != 0)
{
words++;
}
}
}
printf("Words: %i\n", words);
}
This code counts the correct number of letters but always types Words : 0. I haven't done the sentences part. Can I please have some help? If you show me the answer, can you explain why that's the answer?