>#include <iostream.h>
If you can use the string class then you can stop using these old headers.
>#include <cstring.h>
Either you're using an old, nonstandard header, or this should give you a compiler error.
>void main()
No matter how old your compiler is, main always returns int. This has always been the case.
>for (int i=0;i<s.length();i++)
Because you check s[i+1], this should loop to s.length()-1 so that you do not overrun the string's memory boundaries.
>if ((s == space) && (s[i+1] != space))
space is a string, yet s is a char. It would be better to make space a char. Something like this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
int wordcount = 1;
char space = ' ';
cout<<"Enter a sentence: ";
getline(cin,s);
for (int i=0;i<s.length()-1;i++) //Loop to test chars in string
if ((s[i] == space) && (s[i+1] != space))
wordcount++; //If no double space occurs then increment wordcount
cout<<"Number of words equals: "<<wordcount<<endl;
}
You also have issues with short strings and empty strings or strings with nothing but spaces. Perhaps a new algorithm is in order.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,483
Solved Threads: 1,407
Skill Endorsements: 54