C++ function to count all the words in a string

I was asked this during an interview and apparently it’s an easy question but it wasn’t and still isn’t obvious to me.

Given a string, count all the words in it. Doesn’t matter if they are repeated. Just the total count like in a text files word count. Words are anything separated by a space and punctuation doesn’t matter, as long as it’s part of a word.

For example: A very, very, very, very, very big dog ate my homework!!!! ==> 11 words

My “algorithm” just goes through looking for spaces and incrementing a counter until I hit a null. Since i didn’t get the job and was asked to leave after that I guess My solution wasn’t good? Anyone have a more clever solution? Am I missing something?


A less clever, more obvious-to-all-of-the-programmers-on-your-team method of doing it.

#include <cctype>

int CountWords(const char* str)
   if (str == NULL)
      return error_condition;  // let the requirements define this...

   bool inSpaces = true;
   int numWords = 0;

   while (*str != '')
      if (std::isspace(*str))
         inSpaces = true;
      else if (inSpaces)
         inSpaces = false;


   return numWords;