I need to make a function that identifies the number of words by spaces (Ignoring trailing and leading ones). I'm having trouble with the equation that recognizes a space within the string variable. It doesn't count a space like it should. I should be getting the number "2" with the test case I have.
#include<iostream>
#include<string>
using namespace std;
void numWords(string phrase)
{
for (int index = 0; index < phrase.length(); index++)
int words = 0;
int space = 0;
if (phrase[index] == ' ')
{
words++;
space++;
}
}
if (space == 0) //This is for single words with no spaces
{
words++;
}
cout << words << endl;
}
int main()
{
string phrase;
int words = 0;
numWords("hello, world");
//A test case
return 0;
}