Help with calculating how many words are in an array

Hi, I need help counting the number of words in a sentence. Here's the thing, I have a user input a sentence and the program places each word into an array and edits it ("i" is capitalized, duplications are deleted, etc...). Now I would like to put out how many words are in the new sentence. The words are ordered as follows:

i.e.
words[0] = This
words[1] = is
words[2] = computer
words[3] = science

I was thinking of using the below function. I don't know what to put in place of the psuedocode "contains a word"
1
2
3
4
5
6
7
8
9
10
int numberOfWords(string words[])
{
	int counter = 0;
	for (int i = 0; i < 1000; i++)
	{
		if (words[i] == /*contains a word*/)
			counter++;
	}
	return counter;
}
So, we can assume that words is an array of 1000 elements from your code. What differentiates the elements in the array that do not "contain a word" from ones that do?
Have you thought about what is in the positions that don't contain a word?
It might be easier to detect those and increase the counter for every position that does not-not contain a word.
Yeah the array is 1000 elements. I'm assuming the user won't input 1,000 words anyway. As a person I can clearly say that the difference is in that the arrays literally contain a word, but how do I tell c++ that?
Last edited on
What's the difference between "" and "word"?
"" is empty, "word" is not. Is there code for that in which I can put into the above if statement?
Right, the defining characteristic is that strings containing a word have a length of non-zero, so you can compare the lengths to 0, or you can use the aptly named empty method which returns true when the object it is called on is empty.

if(words[i].empty() != true) or equivalently: if (!words[i].empty())
"" has a fixed size that none of your words could ever have.
http://www.cplusplus.com/reference/string/string/size/
if (words[i].size() != 0) ...

or you just compare something like "if (words[i] != "") counter++;"
http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp
Sweet, thanks for the help guys! Can't believe I couldn't see that simple solution!
Topic archived. No new replies allowed.