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.
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!
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 ( constchar *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.