title: C++ How to identify the number of words by spaces using a function
body: <p>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. </p>
  
  <pre><code>#include&lt;iostream&gt;
  #include&lt;string&gt;
  using namespace std;
  
  void numWords(string phrase)
  {
      for (int index = 0; index &lt; 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 &lt;&lt; words &lt;&lt; endl;
  }
  
  int main()
  {
      string phrase;
      int words = 0;
  
      numWords("hello, world");
      //A test case
  
      return 0;
  }
  </code></pre>