So, we were given this program in class. "Write a Program in C to count the number of words in a sentence input by the user." This is what i could come up with, but the number of words is always one less than what is the correct number. My teacher told everyone to just add 1 to the word count before printing it. I think it has a bug, if we don't enter any words, i.e. , press Enter instead of typing,the program suggested by my teacher would still give word count as 1 not 0. Do you know of any way to get proper word count without just adding 1 at the end? Code:
My code(giving 1 less than correct) :
#include <stdio.h>
#include <string.h>
void main()
{
char s[200];
int count = 0, i;
printf("enter the string\n");
gets(s);
for (i = 0;i<strlen(s);i++)
{
if (s[i] == ' ')
count++;
}
printf("number of words in given string are: %d\n", count);
}
You are counting the amount of non-words, but you should be counting the amount of words.
If a word is defined as a sequence of one or more letters, your code might go as:
It's just that you're counting spaces, this would also be incorrect if the user ended the string with a bunch of spaces. Try something like this:
As other users have commented, your program is susceptible to many other issues depending on the string inputed. The example I have posted assumes that anything that is not a space is a letter and if you find at least one letter, than that's a word. Instead of boolean values you could use a counter to make sure that the word is at least a certain length. You could also check to see that it is not a number or symbol by either writing your own regex function or using an existing one. As others have said there is a lot more you can do with this program, but I've provided an example to point you in the right direction.
One improvement would be to handle lines that contain multiple spaces between words or tabs, while still considering a simple return
'\n'
as a word. Usinggetline
provides a number of advantages including providing the number of characters read. Here is an example of the approach:Edit logic simplified:
output: