Hey guys i was wondering if any of you could help here. I've looked around the forums and found a few topics on word_count, the problem is that they use codes that my class hasn't gone into yet so i cant use either.

My problem is that we are supposed to make a program that let's us input a sentence, then it will show the letter count, write the letters 1 letter per line, then show word count.
I was able to do the 1st 3 but for some reason my program wont print the number of words, it's always 0. Can anyone help me out?

#include <stdio.h>
#include <ctype.h>

void input(char *str);
int Ecount(char *str);
void Display(char *str);
void Wcount(char *str);

void main(void)
{
	char S[50];
	int count;

	printf("Input a string: ");
	input(S);
	count = Ecount(S);
	printf("There are %d number of characters.", count);
	printf("\n\n");
	Display(S);
   Wcount(S);
}

void input(char *str)
{
	int i=-1;
	do
	{
		i++;
		scanf("%c", &str[i]);
	}
	while (str[i] !='\n');

	str[i]='\0';
}

int Ecount(char *str)
{
	int i;
	i=0;
	while (str[i] !='\0')
		i++;
	return i;
}

void Display(char *str)
{
	int i;
	i=-1;
	while (str[i] !='\0')
	{
		i++;
		printf("%c\n", str[i]);
	}
}

void Wcount(char *str)
{
	int i=0, word_count=0;
	while (str[i] !='\0')
		i++;
	{
		if( isspace(str[i]) && !isspace(str[i+1]))

			word_count++;

		i++;
		printf("\nThere are %d words.", word_count);
	}

}

There are a few thing wrong with your code :
- you're incrementing 'i' twice in your word_count function. That's not good. You're missing characters because of this and you'll probably run out of array-bounds.

- this: printf("\nThere are %d words.", word_count) should not be inside that loop. It'll get executed more times then you want

- Why use isspace() when you can just say: if (str[i] == ' ') - and very important:

while (str[i] !='\0')
i++;
{
	if( isspace(str[i]) && !isspace(str[i+1]))

What happens when i is at the last character and the code in red is executed? then your accessing an element that isn't part of the array --> Crash

Also it will still tell you one less than the actual number of words in the sentence. Because you are counting the spaces not the words. eg

Sentence-> I am a good boy
spaces-> 4, word_count = 4 !!
actual number of words = 5.

You can increment word_count after the loop once more to correct that.

>This looks like a C-code more than C++ and should have been posted there.

how did you do the highlights?

anyway I did the changes but about the

if (str == ' ')

will it work even if the space is at the start? god knows why but teacher said it should work even if theres a space in the start.

>This looks like a C-code more than C++ and should have been posted there.

Really? i just started taking up computer this sem so i cant tell the difference. I posted it here because the program that our teach lets us use is Borland C++ 4.5

Then you can first move the pointer to the starting of the first word.some thing like this

while (str[i++] == ' '); // move the pointer to starting of first word
while (str[i] !='\0')
	{... your code..
..

What if there are extra spaces at the end of the string? How do you plan to work that?

What if there are two or more spaces between two words?
So you should skip any initial and final spaces, and count any intermediate spaces as one even if there are more than one.
And then add one (as long as you found at least one non-space on the line, otherwise there are zero words).

took all your advice and abit of tinkering on my own and it works!

oh and about the if theres more then 1 space or if theres a space in end of string... Honest to god i don't know why but my program doesnt have a problem with either for some reason... hehe just pure luck i guess. XD

The real problem here is recognition of a word. And as we all know word is a linguistic concept and we cannot be fool proof while programming for such concepts.

The only way I see is to implement AGNI's method for the start and move assuming the sentence is a grammatical English sentence where we can apply :

NO of words = No of spaces from start till '\0' + 1

You can alter "Input String" as "Input a Simple English sentence" or something as inputs generating errors can be written infinitely.

Secondly you can take your input string as:

char String[50];
printf("Input a Simple English sentence");
scanf("%s",String);

Rather than taking it character by character.

There are a few thing wrong with your code :
- you're incrementing 'i' twice in your word_count function. That's not good. You're missing characters because of this and you'll probably run out of array-bounds.

Not really. There loop only increments i . That's the only real problem.

- Why use isspace() when you can just say: if (str[i] == ' ')

Because isspace() will work with not only a SPACE but TAB, and the ending \0. As well as other characters. It's a much better way to go.

- and very important:

while (str[i] !='\0')
i++;
{
	if( isspace(str[i]) && !isspace(str[i+1]))

What happens when i is at the last character and the code in red is executed?

Nothing. The loop ends when the end is reached. Compares the last character with \0, which is part of the string.

Also it will still tell you one less than the actual number of words in the sentence. Because you are counting the spaces not the words. eg

Nope. Not with isspace() .

>This looks like a C-code more than C++ and should have been posted there.

Really? i just started taking up computer this sem so i cant tell the difference. I posted it here because the program that our teach lets us use is Borland C++ 4.5

If you are taking a C++ course, the code is C++. It's just primitive. No one can expect you to know the difference if your instructor hasn't explained the difference.

What if there are two or more spaces between two words?

The code works fine in this case. The program only increments when a SPACE and a non-SPACE are next to each other. That works fine with two consecutive SPACEs.

So you should skip any initial ... spaces...

This is the only real advice given in this thread. Initial SPACEs will mess up the count.

If you are taking a C++ course, the code is C++. It's just primitive. No one can expect you to know the difference if your instructor hasn't explained the difference.

If the instructor hasn't explained the difference we can do, and that's why i pointed it out. It was more of a piece of info than anything else.

Also it will still tell you one less than the actual number of words in the sentence. Because you are counting the spaces not the words. eg

Nope. Not with isspace() .

really?? Why don't you take his code, run it as it is and check the output?

I really don't see why this has to be so hard.

Just loop through each character, find the start and end of each word, then increment the word count.
I guess this is the general idea of what you want:

int wordCount(char *text) {
  int count = 0;

  for (int i = 0; text[i]; ++i) {
    // Find start of word
    while ( isspace(text[i]) )
      ++i;

    // Find end of word
    while ( text[i] && !isspace(text[i]) )
      ++i;

    // Increase word index
    if ( !isspace(text[i-1]) )
      ++count;
  }

  return count;
}

Hope this helps.

I really don't see why this has to be so hard.

No one said it was particularly difficult; we were just trying to help without posting the answer. BTW, your solution does not work for a string of only spaces.

>BTW, your solution does not work for a string of only spaces.
Does for me.

>No one said it was particularly difficult; we were just trying to help without posting the answer.
Well, the poster seems to be tackling this the hard way, I guess it would help to provide an easier solution / technique.

If the instructor hasn't explained the difference we can do, and that's why i pointed it out. It was more of a piece of info than anything else.

really?? Why don't you take his code, run it as it is and check the output?

Sure. Just the minor change correcting his loop I get

d:\wjp>x
Input a string: this is a test

There are 4 words.
d:\wjp>x
Input a string: this   is   a    test

There are 4 words.
d:\wjp>

Is this OK? :icon_rolleyes:

Please tell be what I did wrong...

#include <stdio.h>
#include <ctype.h>

void input(char *str);
int Ecount(char *str);
void Display(char *str);
void Wcount(char *str);

void main(void)
{
	char S[50];
	int count;

	printf("Input a string: ");
	fgets(S, 50, stdin);
   Wcount(S);
}


void Wcount(char *str)
{
	int i=0, word_count=0;
	while (str[i] !='\0')
	{
		if( isspace(str[i]) && !isspace(str[i+1]))

			word_count++;

		i++;
	}
		printf("\nThere are %d words.", word_count);

}

Sure. Just the minor change correcting his loop I get

:) well its getting useless now, I'm sure with 'minor' changes we can achieve a lot with anything.

Mr. OP if you've got what you wanted, please close this thread now.

>>BTW, your solution does not work for a string of only spaces.
>Does for me.
Try this: int main() { printf ("%d\n", wordCount (" ")); } Should be 0; your code gives 1. Easy to fix, though.

>the poster seems to be tackling this the hard way
That's true.

Please tell be what I did wrong...

#include <stdio.h>
#include <ctype.h>

void input(char *str);
int Ecount(char *str);
void Display(char *str);
void Wcount(char *str);

void main(void)
{
	char S[50];
	int count;

	printf("Input a string: ");
	fgets(S, 50, stdin);
   Wcount(S);
}


void Wcount(char *str)
{
	int i=0, word_count=0;
	while (str[i] !='\0')
	{
		if( isspace(str[i]) && !isspace(str[i+1]))

			word_count++;

		i++;
	}
		printf("\nThere are %d words.", word_count);

}
C:\PROGRA~1\MICROS~1.0\VC>test.exe
Input a string:  she sells sea shells at the sea shore but the sea

Output:[B]There are 10 words[/B]

That seems like a wrong output to me.

ummm,..
i came across a similar program in one of the inter collegiate festivals i attended!
it asks to count the occurrences of words in a string!
this one is quite simple n straight!
hope it helps!

#include<stdio.h>
#include<string.h>
main()
{
	int i=0,j,c=0,cnt1;
	static int cnt[100];
	char a[100], b[100][100];
	printf("enter in the string\n");
	gets(a);
	printf("strlen = %d\n",strlen(a));
	for(i=0,c=0;i<strlen(a);i++,c++)
		{
			for(j=0;a[i]!=' '&&i<strlen(a);j++,i++)
			{
				b[c][j]=a[i];
				printf("%c",b[c][j]);
			};
			printf("\n");
		}
	
	for(i=0;i<c;i++)
	{
		for(j=i+1;j<=c;j++)
		{
			if(!strcmp(b[i],b[j]))
			{
				cnt[i]++;
			}
		}
		
	}
	
	
	printf("word\t\ttimes repeated\n");
	for(i=0;i<c;i++)
	{
		for(j=0,cnt1=0;j<i;j++)
		if(!strcmp(b[i],b[j]))
			cnt1++;
		if(!cnt1)
			printf("%s\t\t%d\n",b[i],cnt[i]+1);
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.