I was working on a program in C to count the number of spaces in a sentence. But I haven't managed to get it to work properly. If I enter something like Hello world 1234 how are you the output I'm getting is 3 when the output expected is 5.
My code is :
//Program to count number of words in a given Sentence
#include <stdio.h>
#include <string.h>
int main()
{
char sent[100];
char sentence[] = {' ', '\0'};
printf("\nEnter a sentence :\n");
gets(sent);
strcat(sentence, sent);
int l = strlen(sentence), i = 0, count = 0, countCh = 0;
printf("%d", l);
char ch, ch1;
for (i = 0; i < (l-1); i++)
{
ch = sentence[i];
if (ch == ' ')
{
ch1 = sentence[i+1];
if (((ch1 >= 'A') && (ch1 <= 'Z'))||((ch1 >= 'a') && (ch1 <= 'z')))
count++;
}
}
printf("\nNo of words is : %d", count);
return 0;
}
I used the same logic in Java and it worked fine. Could someone explain whats going wrong?
The following
probably should be
As now " 12345" would not be counted as word.
Also
count
counts the spaces, so the word count is one more: hence 3 instead of 5.Your
sentence
seems to have had the intention of counting the terminatin NUL.If you want to count real words containing letters, use a bool state whether current and prior state of being in a letter differ.
As mentioned overflow is possible with your code.
The problem in your code is with the definition of
sentence
. When you leave out the array dimension and initialize it, the size of the array will be determined by the length of the initializer.Quoting the man page of
strcat()
That is, the program will invoke undefined behavior.
This way,
sentence
has certainly way less memory than it it supposed to hold. Moreover,strcat()
is not at all required there.The correct way to do it will be
sentence
with a proper dimention, likechar sentence[MAXSIZE] = {0};
, whereMAXSIZE
will be a MACRO having the size of your choice.fgets()
to read the user input.isspace()
(fromctype.h
) in a loop to check for presence of space in the input string.