I want to count the words in a given string by counting the spaces between them. Here's the code that i've tried.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
int t,i,b=1;
char a[100];
printf("Enter a sentence: ");
gets(a);
t=strlen(a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]=' ')
{
b++;
}
}
printf("The number of words in the above sentence are %d",b);
getch();
}
But i am unable to get the output. I keep getting wrong number of words.
Thanks. :D
You are using the assignment operator =
for comparison
if(a[i]=' ')
you need ==
if(a[i] == ' ')
some people use this
if (' ' == a[i])
to prevent this kind of mistake.