#include <stdio.h>
#include <cs50.h>
#include <string.h>
int count_letters(string text);
int count_words(string text);
int count_sentences(string text);
int main(void)
{
// Get user input and count letters
string Text = get_string("Text: ");
int letters = strlen(Text);
printf("letters = %d \n", letters);
// Count words in input
int n = 1;
for (int i = 0; i< n; i++)
{
if (text[i] == ' ' && text[i+1] != ' ')
{
words++;
}
printf("words = %d \n". words);
}
}
-
1Please cut and paste the actual code into your question(s) so that people can test. Nobody wants to transcribe code from an image. Also, without all of the code, including functions, it's difficult to test.– Cliff BCommented Sep 5, 2023 at 0:07
-
please format the code as code. this is not legible.– UpAndAdamCommented Sep 6, 2023 at 15:35
1 Answer
You are using n
as a bounds for your loop in counting the words, but n
was assigned the value 1
. You would most certainly want to use letters
instead. Given these problems I would suggest that you rewatch the lesson video. also you are comparing text[i]
to ''
which will never be true. This shouldn't even compile.
beyond that you need to make sure that your i+1
is still less than length
as well.
suggest checking the five primary corner cases before moving on:
- text is a single word
- text starts with a space then a word
- text starts with a word ends with a space
- text has two words seperated by a space
- text has two words with a space before and after each