Counting the number of words in a string

I am trying to count the number of words in a string. I am going to do this by counting the number of spaces in that string. My program will not run, and I cannot figure out why. It says that on the for line, "ISO C++ forbids comparison between pointer and integer." Where am I going wrong?

I am trying to have it loop through each character of the string. So I want it to look at "I", do nothing, look at " ", print 1, look at "a", do nothing, etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string.h>
#include <cstdlib>

using namespace std;

int main()
{
  char sentence[50];

  strcpy(sentence, "I am Legend.");

    for (sentence == 0, sentence < 50, ++sentence)
        {
        char space = ' ';
        if (sentence = space)
            cout << char '1';
        }

    return 0;
}


Last edited on
The sentence is declared as an array

char sentence[50];

and you are trying to assign it an integer in the loop

for (sentence == 0, sentence < 50, ++sentence)

You should read a book on C++ about arrays and how to access their elements.
Also, the for loop elements are separated by ";", not ",". And "sentence = space" assigns space to sentence, you want the "==" operator. Lastly, it's helpful to know that c-style strings are NULL terminated - test for that to determine where sentence ends once you get your loop working, but do not go through all 50 potential elements, most of them have NOT been initialized!
And instead of

1
2
3
char sentence[50];

strcpy(sentence, "I am Legend.");


it is simpler to write

char sentence[] = "I am Legend.";

and the loop rewrite as

1
2
3
4
for ( const char *p = sentence; *p; ++p )
{
   /* body of the loop */
}


Also standard headers shall be written as <cstring> and <cstdlib>. And you need not to include header <cstdlib> because no declaration is used from it.
Last edited on
Topic archived. No new replies allowed.