1. ## A simpler way...

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;
}```

2. This is pretty rushed.. but it seems to work - and will even work around tabs spaces and commas - it is relatively easy to modify to work with other delimeters too.
Code:
```#include <iostream>
#include <string>

using namespace std;

int main(void)
{
char strbuff[256];
char seps[] = ",\t\n ";
char *tok;
int words = 0;

cout << "Enter a string: ";
cin.getline(strbuff, 255, '\n');

tok = strtok(strbuff, seps);

while (tok)
{
cout << tok << endl;
tok = strtok( NULL, seps );
words++;
}

cout << "The number of words are: " << words << endl;

return 0;
}```

3. Code:
```#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main ()
{
string foo;

getline(cin,foo);

cout << endl << "You typed ";
cout << count(foo.begin(),foo.end(),' ') + 1;
cout <<" words" << endl;
}```

4. Oh god, that is so much simpler, Heh heh

5. Fordy, there's a problem with your program.

The amount of words isn't necissarily equal to the number of spaces plus one. What if someone uses two spaces? You have to account for that as well!

6. Originally posted by Polymorphic OOP
Fordy, there's a problem with your program.

The amount of words isn't necissarily equal to the number of spaces plus one. What if someone uses two spaces? You have to account for that as well!

Code:
```#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

bool IsSpace(char c){
static char prev = '\0';
char ret = (c == ' ' && prev != ' ');
prev = c;
return ret;
}

int main ()
{
string foo;

getline(cin,foo);

cout << endl << "You typed ";
cout << count_if(foo.begin(),foo.end(),IsSpace) + 1;
cout <<" words" << endl;
}```