For no particular reason I wrote an algorithm to count how many words in a string. I wrote it and it seemed pretty complicated for such a simple thing. What do you think?Code:// counts the words in a string by
// counting the spaces in it
#include <iostream.h>
#include <string.h>
int main ()
{
char foo[500]; // buffer string
int spaces = 0; // amount of spaces
cin.getline(foo, 500);
cout << endl;
for(unsigned int i = 0; i < strlen(foo); i++)
{
if(foo[i] == ' ')
{
if(foo[i-1] != ' ')
{
spaces++;
}
}
}
if(foo[0] == ' ')
{
spaces--;
}
for(unsigned int j = (strlen(foo) - 1); j > 0; j--)
{
if(foo[j] == ' ')
{
spaces--;
}
else
{
break;
}
}
spaces += 1; // add one to make up for no space before first word
cout << "You typed " << spaces << " words\n";
return 0;
}